简体   繁体   中英

How to merge multiple json arrays into one array swift sub array in Javascript?

I have two json arrays :

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

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

I would like to merge two arrays like as follows : Is it possible to have the solution by 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"}
    ] 

I tried to use Let however I couldn't find the way to manipulate switch the subarray :

     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;

The result is like this :

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

Thanks in advance.

You can use .map() with 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; } 

@Mohammad Usman has a better answer but one simpler to understand is to create a new object with the desired values and push it into the resulting array. Something as follows:

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
    });
}

Here result will have the desired output.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM