gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 06:19:12 25 4
gpt4 key购买 nike

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

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);

关于javascript - 使用另一个对象数组和单个对象构造一个对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54254478/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com