首页 > 解决方案 > 如何将字符串数组复制到对象中

问题描述

我有一个字符串数组和一个对象:

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

标签: javascript

解决方案


你可以简单地使用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);


推荐阅读