我想将一个新数组附加到现有数组。
var input1 = [ { name: 'one' }, { name: 'two' }, { name: 'three' } ];
var input2 = [ { age: '1' }, { age: '2' }, { age: '3' } ];
result = [ { name: 'one', age: '1' }, { name: 'two', age: '2' }, { name: 'three', name: 'three' } ];
这是我的尝试,但它不起作用:
var original = "one,two,three";
var myarray = [{ age: '1' }, { age: '2' }, { age: '3' }];
// this myarray could ALSO be an empty [] array.
myarray += original.split(',').map(s => ({name: s}));
console.log(myarray)
请帮助实现此结果。谢谢 (这不是一个重复的问题,因为我们正在处理其中一个数组长度的可能差异。)
答案 0 :(得分:1)
如果需要处理两个输入数组大小不同的情况,则必须迭代最大长度并输出两个输入对象的串联数组。以下是如何做到这一点的示例:
var input1 = [ { name: 'one' }, { name: 'two' }, { name: 'three' } ];
var input2 = [ { age: '1' }, { age: '2' }, { age: '3' } ];
var output = [];
var maxLength = Math.max(input1.length, input2.length);
for (var i = 0; i < maxLength; i++) {
// here we create a new object which is a combination
// of the item from both input arrays and add it to output
output.push(Object.assign({}, input1[i], input2[i]));
}
console.log(output);
输出数组将是最长输入数组的长度。
答案 1 :(得分:0)
如果要合并两个数组中相同索引的对象,然后返回一个新数组,可以执行以下操作:
result = input1.map((obj, index) => ({
...obj,
...input2[index]
}))
使用工作代码段进行编辑:
const input1 = [ { name: 'one' }, { name: 'two' }, { name: 'three' } ];
const input2 = [ { age: '1' }, { age: '2' }, { age: '3' } ];
function mergeObjectsInArray(arr1, arr2) {
return arr1.map((obj, index) => ({
...obj,
...arr2[index]
}));
}
console.log(mergeObjectsInArray(input1, input2))
答案 2 :(得分:0)
如果两个数组的长度相同,则可以循环其中一个,并且可以使用Object.assign()来合并对象。例如:
var input1 = [ { name: 'one' }, { name: 'two' }, { name: 'three' } ];
var input2 = [ { age: '1' }, { age: '2' }, { age: '3' } ];
var x = [];
for (i in input1) {
x[i] = Object.assign(input1[i], input2[i])
}
变量x将保留您想要的值。