将数组值转换为对象值

时间:2017-06-27 19:46:59

标签: javascript arrays object

如何转换此数组

[ { africa: 1 },
  { culture: 1 },
  { feminism: 3 },
  { 'feminists rising': 1 },
  { law: 1 } ]

这样的事情

someObj = {africa: 1, culture: 1, feminism: 3, 'feminists rising': 1, law: 1}

3 个答案:

答案 0 :(得分:1)

将数组传播到Object#assign



const data = [{"africa":1},{"culture":1},{"feminism":3},{"feminists rising":1},{"law":1}];

const result = Object.assign({}, ...data);

console.log(result);




答案 1 :(得分:0)

const raw = [
  {
    africa: 1
  },
  {
    culture: 1
  },
  {
    feminism: 3
  },
  {
    'feminists rising': 1
  },
  {
    law: 1
  }
];

console.log(raw.reduce((acc, next) => {
  const key = Object.keys(next)[0];
  acc[key] = next[key];
  return acc;
}, {}));

答案 2 :(得分:0)

const subjects = [
  {africa: 1},
  {culture: 1},
  {feminism: 3},
  {'feminists rising': 1},
  {law: 1}
];

使用Object.assign()方法将单个对象的列表混合为空数组。为了从对象数组生成列表,使用扩展语法(...)。

const obj = Object.assign({}, ...subjects);