在 JavaScript 中改变对象

有用的提示:请考虑阅读底部的“目的是什么”部分,因为我什至可能没有最好的方法开始。谢谢。


嘿!所以我有这个:


parent: {

    child1: {

        prop: 'hi there'

    },

    child2: {

        prop: 'hey there'

    }

}

我想运行一些值映射魔法来让它变成这样:


newObj: {

    child1: 'hi there',

    child2: 'hey there'

}

我希望映射函数(或此过程的正确名称)本质上采用prop中每个子项的值parent,并将该值设置value为 a的部分,该部分key带有与 on 相同的名称(parent如果有意义的话)。


每个子对象上的属性是否总是命名为prop?

是的。


为什么不从一开始就这样定义呢?

因为除了prop我需要使用的属性之外,我还有其他属性。


目的是什么?

我正在使用 Laravel。当我将其发送到服务器进行验证时,我必须验证child1.prop而不是child1,这意味着错误消息发送回:


child1.prop :“有些东西是无效的”


......我希望它是


child1:"有些东西是无效的"'


如果有更好的方法,请提出建议。


qq_花开花谢_0
浏览 124回答 1
1回答

qq_遁去的一_1

只需添加@Chris G 的答案,其他用户就可以轻松找到它:const parent = {  child1: {    prop: 'hi there'  },  child2: {    prop: 'hey there'  }};const newObj = Object.entries(parent).reduce((a, [key, { prop }]) => ({ ...a, [key]: prop }), {});out.textContent = JSON.stringify(newObj);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript