如何连接来自2个数组的数据[重复]
Posted
技术标签:
【中文标题】如何连接来自2个数组的数据[重复]【英文标题】:How to join data from 2 array [duplicate] 【发布时间】:2020-11-19 20:38:00 【问题描述】:我需要加入来自 2 个数组的数据
示例数据:
const data1 = [
"firstName":"Donald",
"firstName":"Mickey"
]
const data2 = [
"lastName":"Duck",
"lastName":"Mouse"
]
我想要的结果是:
const final = [
"firstName":"Donald", "lastName":"Duck",
"firstName":"Mickey", "lastName":"Mouse"
]
怎么做?
【问题讨论】:
【参考方案1】:const data1 = [
"firstName":"Donald",
"firstName":"Mickey"
]
const data2 = [
"lastName":"Duck",
"lastName":"Mouse"
]
const result = data1.map((obj, index) => ( ...obj, ...data2[index] ));
console.log(result);
【讨论】:
你可以这样写返回对象: (obj, index) => ( ...obj, ...data[index] )【参考方案2】:你也可以使用 for 循环:
let finalRes = [];
const data1 = [ firstName: "Donald" , firstName: "Mickey" ];
const data2 = [ lastName: "Duck" , lastName: "Mouse" ];
for (var i = 0; i < data1.length; i++)
finalRes.push( ...data1[i], ...data2[i] );
console.log(finalRes);
【讨论】:
【参考方案3】:const data1 = [
"firstName": "Donald"
,
"firstName": "Mickey"
]
const data2 = [
"lastName": "Duck"
,
"lastName": "Mouse"
]
const result = [];
data1.forEach((aData, index) =>
result.push(
...aData,
...(data2[index])
)
)
console.log(result);
【讨论】:
以上是关于如何连接来自2个数组的数据[重复]的主要内容,如果未能解决你的问题,请参考以下文章