我有两个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"}]
谢谢。
答案 0 :(得分:3)
您可以将.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; }
答案 1 :(得分:0)
@Mohammad Usman有一个更好的答案,但更容易理解的是创建一个具有所需值的新对象并将其推入结果数组。如下:
users = [
{"userId": 9},
{"userId": 14}
];
data = [
{"rid": 1},
{"mid": 201}
];
result = [];
for (var i = 0; i < users.length; i++) {
result.push({
"rid": data[0].rid,
"mid": data[1].mid,
"userId": users[i].userId
});
}
这里result
将具有所需的输出。