我这里有一个数组:
var array = [
[
['firstName', 'Nork'], ['lastName', 'James'], ['age', 22], ['position', 'writer']
],
[
['firstName', 'James'], ['lastName', 'Rodel'], ['age', 25], ['position', 'programmer']
]
];
我创建了一个函数,它将我的函数转换为 obj 数组,如下所示:
[
{firstName: 'Nork', lastName: 'James', age: 22, position: 'writer'},
{firstName: 'James', lastName: 'Rodel', age: 25, role: 'programmer'}
]
所以我创建了一个函数来执行此操作。但是我不确定从哪里开始才能合并它们。
function changeData(array) {
var obj = { };
}
changeData(array);
有什么帮助吗?
最佳答案
The
map()
method creates a new array with the results of calling a provided function on every element in this array.
Thereduce()
method applies a function against an accumulator and each element in the array (from left to right) to reduce it to a single value.
var array = [
[
['firstName', 'Nork'],
['lastName', 'James'],
['age', 22],
['position', 'writer']
],
[
['firstName', 'James'],
['lastName', 'Rodel'],
['age', 25],
['position', 'programmer']
]
];
function mergeObjectArray(array) {
return array.map(function(el) {
return el.reduce(function(a, b) {
a[b[0]] = b[1];
return a;
}, {})
});
}
console.log(mergeObjectArray(array));
关于javascript - 合并数组到对象数组 JavaScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43753457/