[英]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. 您可以对
Object.keys()
和ES6扩展语法使用map()
。
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));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.