我有3个独立的数组,每个数组中有3个对象:
[{Index: 1}, {Index: 2}, {Index: 3}]
[{Placement: 'Wall'}, {Placement: 'Roof'}, {Placement: 'Door'}]
[{Color: 'GREEN'}, {Color: 'WHITE'}, {Color: 'BLACK'}]
我正在努力实现以下目标:
[
{
Index: 1,
Placement: 'Wall',
Color: 'GREEN'
},
{
Index: 2,
Placement: 'Roof',
Color: 'WHITE'
},
{
Index: 3,
Placement: 'Door',
Color: 'BLACK'
}
]
有没有办法用JS做到这一点? 我已经尝试将这些与下划线和jquery的合并/扩展相结合,但我只获得一个对象中的所有值或具有单个值的对象(例如颜色)。非常感谢。
答案 0 :(得分:3)
使用ES6,您可以使用Array#map
和Object.assign
var array1 = [{ Index: 1 }, { Index: 2 }, { Index: 3 }],
array2 = [{ Placement: 'Wall' }, { Placement: 'Roof' }, { Placement: 'Door' }],
array3 = [{ Color: 'GREEN' }, { Color: 'WHITE' }, { Color: 'BLACK' }],
combined = array1.map((a, i) => Object.assign({}, a, array2[i], array3[i]));
console.log(combined);
.as-console-wrapper { max-height: 100% !important; top: 0; }
针对多个阵列的唯一ES5解决方案。
var array1 = [{ Index: 1 }, { Index: 2 }, { Index: 3 }],
array2 = [{ Placement: 'Wall' }, { Placement: 'Roof' }, { Placement: 'Door' }],
array3 = [{ Color: 'GREEN' }, { Color: 'WHITE' }, { Color: 'BLACK' }],
combined = [array1, array2, array3].reduce(function (r, a) {
a.forEach(function (b, i) {
Object.keys(b).forEach(function (k) {
r[i] = r[i] || {};
r[i][k] = b[k];
});
});
return r;
}, []);
console.log(combined);
.as-console-wrapper { max-height: 100% !important; top: 0; }
答案 1 :(得分:2)
array
var a = [{
Index: 1
}, {
Index: 2
}, {
Index: 3
}];
var b = [{
Placement: 'Wall'
}, {
Placement: 'Roof'
}, {
Placement: 'Door'
}];
var c = [{
Color: 'GREEN'
}, {
Color: 'WHITE'
}, {
Color: 'BLACK'
}];
var arr = [];
for (var i = 0, len = a.length; i < len; i++) {
var obj = {};
obj.Index = a[i].Index;
obj.Placement = b[i].Placement;
obj.Color = c[i].Color;
arr.push(obj);
}
console.log(arr);
答案 2 :(得分:0)
经典和ES6版本中更通用的解决方案:
// classic version
function mergeSameLengthArrays(arrays) {
var length = arrays[0].length;
var merged = [];
//instead of this function you can use its equivalent from jquery or lodash library
function mergeObjects(obj1, obj2){
var mergedObj = {};
for (var attr in obj1) {
mergedObj[attr] = obj1[attr];
}
for (var attr in obj2) {
mergedObj[attr] = obj2[attr];
}
return mergedObj;
}
for (var i = 0; i < length; i++) {
arrays.forEach(function (arr) {
merged[i] = mergeObjects(merged[i] || {}, arr[i]);
});
}
return merged;
}
// ES6 version
function es6MergeSameLengthArrays(arrays) {
return arrays.reduce((acc, arr) =>
arr.map((item, i) =>
Object.assign(acc[i] || {}, item)
), []);
}
// Usage examples
var a1 = [{a: 1}, {a: 2}];
var a2 = [{b: 1}, {b: 2}];
console.log('classic version:', mergeSameLengthArrays([a1, a2]));
console.log('ES6 version:', es6MergeSameLengthArrays([a1, a2]));
&#13;