简体   繁体   English

将 Javascript 嵌套 Object 逐一更新

[英]Update Javascript nested Object one by one

I have this kind of object:我有这种object:

  {
   a:{name:'a'},
   b:{name:'b'},
   c:{name:'c'},
}

And my goal is to add new key/value pair to each object.我的目标是为每个 object 添加新的键/值对。 So final result shall look like this:所以最终结果应该是这样的:

 {
   a:{name:'a',newField:false},
   b:{name:'b',newField:false},
   c:{name:'c',newField:false},
}

So far I've tried to put my current object into array and loop through but I had no success at all since I am getting only first level of key/value pairs.到目前为止,我已经尝试将我当前的 object 放入数组并循环,但我根本没有成功,因为我只获得了第一级键/值对。

Any suggestions please?请问有什么建议吗?

The easiest way to accomplish this it to use a for...in loop.完成此操作的最简单方法是使用for...in循环。

 const data = { a: { name: 'a' }, b: { name: 'b' }, c: { name: 'c' }, }; for (let key in data) { data[key].newField = false; } console.log(data);
 .as-console-wrapper { top: 0; max-height: 100%;important; }

If you do not wish to mutate the data you can try the following:如果您不想改变数据,可以尝试以下操作:

 const data = { a: { name: 'a' }, b: { name: 'b' }, c: { name: 'c' }, }; const copy = Object.fromEntries(Object.entries(data).map(([key, val]) => [key, {...val, newField: false }])); console.log(copy);
 .as-console-wrapper { top: 0; max-height: 100%;important; }

If you're happy mutating the object rather than creating a new one use a for...in loop .如果您愿意改变 object 而不是创建一个新的,请使用for...in循环

 const obj = { a: {name:'a'}, b: {name:'b'}, c: {name:'c'}, }; for (let key in obj) { obj[key].newField = false; } console.log(obj);

a for..in should do it一个 for..in 应该这样做

for (const key in yourObject) {
  yourObject[key].newField = false
}

try this:尝试这个:

const orig_obj = {
   a:{name:'a'},
   b:{name:'b'},
   c:{name:'c'},
};

Object.keys(orig_obj).forEach((key) =>{
  orig_obj[key].newField = false;
});

console.log(orig_obj);
// Output:
/*
{
   a:{name:'a',newField:false},
   b:{name:'b',newField:false},
   c:{name:'c',newField:false},
}
*/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM