如何连接来自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个数组的数据[重复]的主要内容,如果未能解决你的问题,请参考以下文章

当另一个数组有一个数字(值)时如何匹配2个数组的字符串值

如何返回具有真/假值比较 2 个数组的数组?

如何创建一个包含 2 个数组的字典?

N 个数组的笛卡尔积

c# 随机单个三个数作为一组,不重复之前出现的一组数据

如何用 LINQ 重写笛卡尔积