gpt4 book ai didi

javascript - 如何在Javascript中将多个json数组合并为一个数组swift子数组?

转载 作者:行者123 更新时间:2023-11-28 17:20:56 31 4
gpt4 key购买 nike

我有两个 json 数组:

     1) 
[
{
"userId": 9
},
{
"userId": 14
}
]

2)
[{"role": "1", "group": "3"}, {"role": "1", "group": "2"}]

我想合并两个数组,如下所示:可以用javascript解决吗?

    [
{"userId":9,"role":"1","group":"2"},
{"userId":14,"role":"1","group":"2"}
{"userId":9,"role":"1","group":"3"},
{"userId":14,"role":"1","group":"3"}
]

我尝试使用 Let 但是我找不到操作切换子数组的方法:

     let arr1 = 
[{ "userId": 9 }, { "userId": 14 }]
let arr2 = [{"role": "1","group": "3"}, {"role": "1","group": "2" }]

let result = arr1.map(o => Object.assign(o, ...arr2));

console.log(result);
return result;

结果是这样的:

    [{"userId":9,"role":"1","group":"2"},{"userId":14,"role":"1","group":"2"}] 

提前致谢。

最佳答案

您可以将.map()Object.assign()结合使用:

let arr1 = [{"userId": 9}, {"userId": 14}],
arr2 = [{"rid": 1}, {"mid": 201}];

let result = arr1.map(o => Object.assign(o, ...arr2));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于javascript - 如何在Javascript中将多个json数组合并为一个数组swift子数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52504759/

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