简体   繁体   中英

Union arrays from all object properties

Lets say I have an object:

    let obj={
         hash1:{
            images:[img1,img2....]
         }
         hash2:{
            images:[img100,img200....]
         }  
         hash3:{
             images:[img1000,img2000....]
         }
      ...       
}

I want to union all those arrays in one array. I understand that I can use next code:

let unionArray=[];

Object.values(obj).forEach((item)=>{
unionArray=unionArray.concat(item.images)
});

Are there more elegant way to do such task eg with some framework or in one line coding.

数组约简在这里非常好:

let union = Object.values(obj).reduce((c, i) => c.concat(i.images), []);

You can use map() on Object.keys() and ES6 spread syntax.

 let obj = {"hash1":{"images":["img1","img2"]},"hash2":{"images":["img100","img200"]},"hash3":{"images":["img1000","img2000"]}} var arr = [].concat(...Object.keys(obj).map(e => obj[e].images)); console.log(arr) 

使用Array#map

const union = [].concat(...Object.values(obj).map(v => v.images));

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