gpt4 book ai didi

javascript - 将数组映射到由数组值作为键的对象

转载 作者:行者123 更新时间:2023-12-03 01:20:58 25 4
gpt4 key购买 nike

我需要能够根据数组值从对象中删除对象。

我有一个基础对象:

   const obj = {
one: {
selected: undefined,
},
two: {
selected: undefined,
},
three: {
selected: undefined,
}
};

示例数组是:

const arr = ['one', 'two'];

我尝试这样做:

const mappedObj = arr.map(val => {
if (obj[val]) {
return ({
[val]: {
selected: true
},
});
}

return false;
})

我需要它是:

object: {
one: {
selected: true,
},
two: {
selected: true,
}
}

最佳答案

您可以映射单个对象并将它们分配给单个对象 Object.assignspread syntax ...对于数组。

var object = { one: { selected: undefined, foo: 42 }, two: { selected: undefined }, three: { selected: undefined } },
array = ['one', 'two'],
result = Object.assign(
...array.map(k => ({ [k]: Object.assign({}, object[k], { selected: true }) }))
);

console.log(result);

关于javascript - 将数组映射到由数组值作为键的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51767466/

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