简体   繁体   中英

Merging multiple arrays inside a array of objects into a single array

I have a object where data is an array of objects, inside data object I have one users property which is an array.

I need to get all the users into a single array. I have written using map and concat .

Is there any way I can have a better solution, or this is correct?

See the below snippet.

 var response = {data: [{users: [1,2,3]}, {users: [4,5,6]}]} var users = response.data.map(o => o.users) const usersCollection = [].concat(...users) console.log(usersCollection)

You can use Array.prototype.flat() :

The flat() method creates a new array with all sub-array elements concatenated into it recursively up to the specified depth .

depth | Optional

The depth level specifying how deep a nested array structure should be flattened. Defaults to 1.

 var response = {data: [{users: [1,2,3]}, {users: [4,5,6]}]} var users = response.data.map(o => o.users).flat(); console.log(users);

You can also try with Array.prototype.flatMap() which is identical to a map followed by a call to flat of depth 1 .

var users = response.data.flatMap(o => o.users);

If Using ES6, utilizing the power of spread with Array.reduce

 var response = { data: [{ users: [1, 2, 3] }, { users: [4, 5, 6] }] } var users = response.data.reduce((accumulator, obj) => [...accumulator, ...obj.users], []); console.log(users);

Using ES6 Spread operator you can do the job quick.

var response = {data: [{users: [1,2,3]}, {users: [4,5,6]}]}

let wantedArray = [];
for(let v of response.data){
  wantedArray.push(...v.users);
}

console.clear();
console.log(wantedArray);

The flatMap() method first maps each element using a mapping function, then flattens the result into a new array. It is identical to a map followed by a flat of depth 1, but flatMap is often quite useful, as merging both into one method is slightly more efficient

response.data.flatMap(({users})=>users)

You should be careful with vendor support though if you're running in the browser.

You can use ES6 spread operator

var response = {data: [{users: [1,2,3]}, {users: [4,5,6]}]}    
var NEWARRAY = [];
for(var v of response.data){
  NEWARRAY.push(...v.users);
}
console.log(NEWARRAY);

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