繁体   English   中英

使用另一个对象数组和一个对象构造一个对象数组

[英]Construct an array of objects using another array of objects and a single object

我有一个这样的对象数组:

channels=[
  {name: mega, status: true},
  {name: ant, status: false},
  {name: apl, status: true}
]

我有一个具有这种格式的对象

obj = {0: false, 1: true}

普通对象中的键表示channels数组的索引。 status属性必须更新。

对于以上示例,数据channels应更新为:

channels=[
  {name: mega, status: false},
  {name: ant, status: true},
  {name: apl, status: true}
]

我怎样才能有效地实现这一目标?

一个简单的for循环可以做到:

for (let index in obj) channels[index].status = obj[index];

 const channels=[{name: "mega", status: true}, {name: "ant", status: false}, {name: "apl", status: true}]; const obj={0: false, 1:true}; for (let index in obj) { channels[index].status = obj[index]; } console.log(channels); 

如果您不想变异原始数组,但是想要一个经过修改的新数组,那么:

 const channels=[{name: "mega", status: true}, {name: "ant", status: false}, {name: "apl", status: true}]; const obj={0: false, 1:true}; const result = channels.map(({name, status}, i) => ({name, status: i in obj ? obj[i] : status}) ); console.log(result); 

这个循环应该做到这一点。

 for(var key in obj){
       channels[key].status = obj[key]
    }

您可以使用任何喜欢的方法来遍历obj (在这里,我使用Object.keysobj对象获取键的数组,而forEach遍历它们)并更新字段。 可以用一行代码来实现:

 const channels = [ {name: "mega", status: true}, {name: "ant", status: false}, {name: "apl", status: true} ]; const obj = { "0": false, "1": true }; Object.keys(obj).forEach((item, i) => channels[i].status = obj[i]); /** * If "channels" array is NOT ALWAYS longer than the amount of "obj" properties, * you should add the check for existence, the simpliest one is implemented below: * * Object.keys(obj).forEach((item, i) => channels[i] ? channels[i].status = obj[i] : null); */ console.log(channels); 

在提供的情况下,原始数组会发生突变,如果不是您需要的数组,我建议您看一下map方法,它不会使原始数组发生突变,而是创建一个新数组。

您可以使用forEach()遍历channels数组,并使用Object.assign()覆盖属性。

 let channels = [ {name: 'mega', status: true }, {name: 'ant' , status: false}, {name: 'apl' , status: true } ]; let obj = { 0: false, 1: true }; channels.forEach((o, i) => i in obj ? Object.assign(o, {status: obj[i]}) : o); console.log(channels); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

暂无
暂无

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

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