Helpful note: Consider reading the 'What's the purpose' part at the bottom, as I may not even have the best approach here, to begin with. Thanks.
嘿!所以我得到了这个:
parent: {
child1: {
prop: 'hi there'
},
child2: {
prop: 'hey there'
}
}
我想运行一些值映射魔法,让它变成这样:
newObj: {
child1: 'hi there',
child2: 'hey there'
}
我希望映射函数(或此过程的正确名称)本质上采用 parent
中每个子项的 prop
值,并将该值设置为key
的 value
部分,它与 parent
上的名称相同(如果有意义的话)。
每个子对象的属性是否始终命名为 prop
?
是的。
为什么不从一开始就这样定义呢?
因为除了 prop
之外我还需要使用其他属性。
目的是什么?
我正在使用拉拉维尔。当我将其发送到服务器进行验证时,我必须验证 child1.prop
而不是 child1
,这意味着错误消息发回为:
child1.prop : "Something is invalid"
...我希望它是
child1:"Something is invalid"'
如果有更好的方法,请提出。
最佳答案
只需添加 @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);
关于javascript - JavaScript 中的变异对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58107963/