如何使用JavaScript将两个对象数组合并为单个数组和对象。

huangapple go评论61阅读模式
英文:

how to merge two array of objects into single array and object using javascript

问题

我想知道如何使用JavaScript将两个对象数组合并成一个单一的数组。

var arr1 = [
  {id:1, name: "xxx"}
]

var arr2 = [
 {details:"finance", cost:"100"}
]

尝试过以下方法
var result1 = [...arr1, ...arr2];
var result = Object.assign({}, ...result1)

期望的输出:

[
  {
    id:1, 
    name: "xxx",
    details:"finance", 
    cost:"100"
  }
]
英文:

I would like to know how to merge two array of objects into single array using javascript

var arr1 = [
  {id:1, name: "xxx"}
]

var arr2 =[
 {details:"finance", cost:"100"}
]

Tried.
var result1 = [...arr1, ...arr2];
var result=Object.assign({}, ...result1)



Expected Output
[
{
id:1,
name: "xxx",
details:"finance",
cost:"100"
}
]

答案1

得分: 1

var arr1 = [
  { id: 1, name: "xxx" }
]

var arr2 = [
  { details: "finance", cost: "100" }
]

const result = arr1.map((item, index) => ({ ...item, ...arr2[index] }))

console.log(result)
英文:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

var arr1 = [
  {id:1, name: &quot;xxx&quot;}
]

var arr2 =[
 {details:&quot;finance&quot;, cost:&quot;100&quot;}
]

const result = arr1.map((item, index) =&gt; ({ ...item, ...arr2[index] }))

console.log(result)

<!-- end snippet -->

答案2

得分: 0

只需将 [...arr1, ...arr2] 放入花括号内,并通过数组索引访问:[{...arr1[0], ...arr2[0]}]

英文:

Just inner-wrap you [...arr1, ...arr2] in curly braces and access via array index: [{...arr1[0], ...arr2[0]}]

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

var arr1 = [
  {id:1, name: &quot;xxx&quot;}
]

var arr2 =[
 {details:&quot;finance&quot;, cost:&quot;100&quot;}
]

var result1 = [{...arr1[0], ...arr2[0]}];

console.log(result1)

<!-- end snippet -->

答案3

得分: 0

你也可以连接两个数组然后将整个数组减少以分配给一个新对象

var arr1 = [
  {id:1, name: "xxx"}
]

var arr2 =[
 {details:"finance", cost:"100"}
]

const result = arr1.concat(arr2).reduce(((r, c) => Object.assign(r, c)), {});
console.log(result)

我更喜欢这种方式因为你可以向 concat 函数中添加任意数量的数组
英文:

You can also concat both arrays and then reduce the whole array to assign to a new object:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

var arr1 = [
  {id:1, name: &quot;xxx&quot;}
]

var arr2 =[
 {details:&quot;finance&quot;, cost:&quot;100&quot;}
]

const result = arr1.concat(arr2).reduce(((r, c) =&gt; Object.assign(r, c)), {});
console.log(result)

<!-- end snippet -->

I prefer this because you can add as many arrays as you want to the concat function.

huangapple
  • 本文由 发表于 2023年6月1日 16:51:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/76380178.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定