英文:
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: "xxx"}
]
var arr2 =[
{details:"finance", cost:"100"}
]
const result = arr1.map((item, index) => ({ ...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: "xxx"}
]
var arr2 =[
{details:"finance", cost:"100"}
]
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: "xxx"}
]
var arr2 =[
{details:"finance", cost:"100"}
]
const result = arr1.concat(arr2).reduce(((r, c) => 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论