将包含数组数组的数组转换为包含object的数组

时间:2017-06-10 04:50:05

标签: javascript arrays javascript-objects

我遇到了这个问题。小时候已经过去但无法解决。我很困惑。

有人可以帮我解决这个问题吗?

输入:

[
  [
    ['firstName', 'Joe'],
    ['lastName', 'Blow'],
    ['age', 42],
    ['role', 'clerk']
  ],
  [
    ['firstName', 'Mary'],
    ['lastName', 'Jenkins'],
    ['age', 36],
    ['role', 'manager']
  ]
]

输出:

[{
    firstName: 'Joe',
    lastName: 'Blow',
    age: 42,
    role: 'clerk'
  },
  {
    firstName: 'Mary',
    lastName: 'Jenkins',
    age: 36,
    role: 'manager'
  }
]

1 个答案:

答案 0 :(得分:0)

使用Array#mapArray#reduce方法来获得结果。

var data = [
  [
    ['firstName', 'Joe'],
    ['lastName', 'Blow'],
    ['age', 42],
    ['role', 'clerk']
  ],
  [
    ['firstName', 'Mary'],
    ['lastName', 'Jenkins'],
    ['age', 36],
    ['role', 'manager']
  ]
];

var res = data
  // iterate over the main array
  .map(function(arr) {
    // iterate over the inner array to generate object
    return arr.reduce(function(o, a) {
      // define the object property based on the element
      o[a[0]] = a[1];
      // return object reference
      return o;
      // set initial value as an empty object
    }, {});
  });

console.log(res);

使用ES6 arrow function

var data = [
  [
    ['firstName', 'Joe'],
    ['lastName', 'Blow'],
    ['age', 42],
    ['role', 'clerk']
  ],
  [
    ['firstName', 'Mary'],
    ['lastName', 'Jenkins'],
    ['age', 36],
    ['role', 'manager']
  ]
];

var res = data.map(arr => arr.reduce((o, a) => (o[a[0]] = a[1], o), {}));

console.log(res);