javascript - JavaScript 中的变异对象

标签 javascript arrays object

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 值,并将该值设置为keyvalue 部分,它与 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/

相关文章:

javascript - 如何删除数组中重复对象的两个实例

java - 计算数组中连续项的出现次数

java - 无状态对象的良好实践与否

javascript - 并排迭代两个对象

javascript - 多个选项卡同一 session ,当所有选项卡消失时清除 session

java - 修改 lambda 封闭范围内定义的数组

javascript - 如何显示不连续折线图

python - 重新创建类对象更改一个构造函数参数

php - 我如何通过 Wordpress 使用 jQuery UI?

JavaScript Float32Array 文件