gpt4 book ai didi

javascript - 将数组中的对象属性推送到另一个对象数组中

转载 作者:行者123 更新时间:2023-11-28 12:15:54 26 4
gpt4 key购买 nike

我试图弄清楚如何从一个数组中获取对象并将它们合并到另一个对象数组的对象中。我在 Angular 5 应用程序中使用 Typescript

数组 1:

[
{
"outcomeId": 1,
"outcomeName": "draw",
"stake": 100
},
{
"outcomeId": 12,
"outcomeName": "Gandzasar Kapan FC 2",
"stake": 100000000
}
]

数组2:

[
{
"success": true
},
{
"success": false,
"error": {
"description": "Insufficient balance 989066"
}
}
]

结果数组:

[
{
"outcomeId": 9171077,
"outcomeName": "draw",
"stake": 100,
"success": true
},
{
"outcomeId": 9171076,
"outcomeName": "Gandzasar Kapan FC 2",
"stake": 100000000,
"success": false,
"error": {
"description": "Insufficient balance 989066"
}
}
]

我知道如何使用 .map 循环遍历数组,但我不知道如何使用两个数组然后合并它们。

最佳答案

此方法将创建一个新数组,新数组和旧数组将引用一些对象。

var array1 = [{    "outcomeId": 1,    "outcomeName": "draw",    "stake": 100  },  {    "outcomeId": 12,    "outcomeName": "Gandzasar Kapan FC 2",    "stake": 100000000  }];
var array2 = [{ "success": true }, { "success": false, "error": { "description": "Insufficient balance 989066" } }]

var result = array1.map((o, i) => ({...o, ...array2[i]}))
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

没有 Spread 语法,使用函数 Object.assign

var array1 = [{    "outcomeId": 1,    "outcomeName": "draw",    "stake": 100  },  {    "outcomeId": 12,    "outcomeName": "Gandzasar Kapan FC 2",    "stake": 100000000  }];
var array2 = [{ "success": true }, { "success": false, "error": { "description": "Insufficient balance 989066" } }]

var result = array1.map((o, i) => Object.assign(o, array2[i]));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于javascript - 将数组中的对象属性推送到另一个对象数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49457363/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com