4 回答
TA贡献1813条经验 获得超2个赞
您可以执行以下操作(假设两个数组的长度相同):
array1 = array1.map((el, i) => {
el.num = array2[i];
return el;
});
编辑:对于您的第二种情况,如果您不确定weirdKey将是什么,您可以执行以下操作:
array1 = array1.map((el, i) => {
el.num = Object.values(array2[i])[0];
return el;
});
TA贡献1877条经验 获得超6个赞
以下内容适用于您的两种情况:
let array1 = [{ name: "ABC", add: "XYZ" }, { name: "PQR", add: "CCC" }];
let array2 = [{ weirdKey: 1 }, { weirdKey: 2 }];
array1.forEach((element, i) => {
array1[i].num = array2[i].weirdKey ? array2[i].weirdKey : array2[i];
});
console.log(array1);
TA贡献1848条经验 获得超2个赞
尝试对数组使用 map() 方法
// without weirdKey
let array1 = [{ name: "ABC", add: "XYZ" }, { name: "PQR", add: "CCC" }]
let array2 = [1, 2];
array1.map((item, index) => item.num = (array2[index].weirdKey) ? array2[index].weirdKey : array2[index])
console.log(array1)
// with weirdKey same function
let array3 = [{ name: "ABC", add: "XYZ" }, { name: "PQR", add: "CCC" }]
let array4 = [{ weirdKey: 1 }, { weirdKey: 2 }];
array3.map((item, index) => item.num = (array4[index].weirdKey) ? array4[index].weirdKey : array4[index])
console.log(array3)
TA贡献1836条经验 获得超5个赞
简单的纯函数:
const combineToArrayFn =
(array1, array2, key = '') =>
array1.map((item, i) => ({...item, num: array2[i][key] || array2[i]}));
const newArray = combineToArrayFn(array1, array2);
const newArray1 = combineToArrayFn(array1, array2, 'weirdKey');
添加回答
举报