我遇到了这个问题。小时候已经过去但无法解决。我很困惑。
有人可以帮我解决这个问题吗?
输入:
[
[
['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'
}
]
答案 0 :(得分:0)
使用Array#map
和Array#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);
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);