如何将字符串数组复制到对象中

时间:2018-08-15 09:15:27

标签: javascript

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

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

5 个答案:

答案 0 :(得分:4)

您只需使用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);

答案 1 :(得分:1)

另一种方法是使用reduce method

这将使obj发生突变,并且result将指向obj。意味着更改其中之一会同时更改两者。

const result = arr.reduce((acc, item) => {
    acc[item] = true;
    return acc;
}, obj);

如果您不想突变obj,请使用spread operator

const result = arr.reduce((acc, item) => {
    acc[item] = true;
    return acc;
}, { ...obj });

答案 2 :(得分:0)

const arr = ['abc', 'def'];

const obj = {
  foo: true,
  bar: 42,
};

const result = {...obj}; // don't modify the original obj

arr.forEach(i => result[i] = true);

答案 3 :(得分:0)

您可以复制对象并映射所需的属性。

var array = ['abc', 'def'],
    object = { foo: true, bar: 42 },
    result = Object.assign({}, object, ...array.map(k => ({ [k]: true })));
    
console.log(result);

答案 4 :(得分:0)

怎么样:

Object.assign({}, obj, ...arr.map(x => ({[x]: true})))

演示:

const arr = ['abc', 'def'];
const obj = {foo: true, bar: 42};

const result = Object.assign(obj, ...arr.map(x => ({[x]: true})));

console.log(result);

相关问题