[英]How to construct an array of objects by using the keys of another array of objects and values from the array of arrays?
[英]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.keys
从obj
对象获取键的数组,而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.