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

时间:2018-09-25 18:38:02

标签: javascript arrays json merge

我有两个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"}] 

谢谢。

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将具有所需的输出。