将两个数组合并为一个结果数组

let array1 = [{name:"ABC",add:"XYZ"},{name:"PQR",add:"CCC"}];


let array2 = [1,2]

我希望输出是


array1=[{name:"ABC",add:"XYZ",num:1},{name:"PQR",add:"CCC",num:2}];


而且我还想知道我的 array2 是否也是具有奇怪键名的对象数组,但在结果数组中我想要一个好的键名,例如


let array1 = [{name:"ABC",add:"XYZ"},{name:"PQR",add:"CCC"}];


let array2=[{weirdKey:1},{weirdKey:2}];

但结果数组会像


array1=[{name:"ABC",add:"XYZ",num:1},{name:"PQR",add:"CCC",num:2}];


缥缈止盈
浏览 170回答 4
4回答

慕姐8265434

您可以执行以下操作(假设两个数组的长度相同):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;});

慕哥9229398

以下内容适用于您的两种情况: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);

慕尼黑5688855

尝试对数组使用 map() 方法// without weirdKeylet 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 functionlet 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)

一只甜甜圈

简单的纯函数: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');
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript