我有一个字符串数组和一个对象:
const arr = ['abc', 'def'];
const obj = {
foo: true,
bar: 42,
};
我需要将 arr
中的值添加为 obj
中的键,以便生成的对象如下所示:
const result = {
foo: true,
bar: 42,
abc: true,
def: true,
};
这是我尝试过的:
{ ...obj, ...arr.map(x => ({[x]: true })) }
最佳答案
您可以简单地使用Object.assign()
:
下面给出的示例将改变原始对象:
let arr = ['abc', 'def'];
let obj = {
foo: true,
bar: 42,
};
// Note it will mutate the original object
arr.forEach((e)=> Object.assign(obj, {[e] :true }));
console.log(obj);
如果您不想改变原始对象,请尝试以下操作:
let arr = ['abc', 'def'];
let obj = {
foo: true,
bar: 42,
};
let result = Object.assign({}, obj);
arr.forEach((e)=> Object.assign(result, {[e] :true }));
console.log(result);
关于javascript - 如何将字符串数组复制到对象中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51855991/