[英]How transform object that contain arrays in keys to array of string with certain field?
I just have object, that contains arrays in keys, and I need get array of string with name property.我只有 object,它在键中包含 arrays,我需要获取具有名称属性的字符串数组。 I cope to do it with flat, but probably there is better solution
我可以用flat来做,但可能有更好的解决方案
const testObj = {
first: [ { name: 'Den' }, { name: 'Ben' } ],
second: [ { name: 'Ken} ]
}
Expected result:预期结果:
['Den', 'Ben', 'Ken' ]
My solution:我的解决方案:
const res = Object.keys(testObj).map(key=>{
return testObj[key].map(el=>el.name)
}).flat(1)
You can use flatMap
instead of calling map
and flat
separately.您可以使用
flatMap
而不是分别调用map
和flat
。 Also you can replace Object.keys
with Object.values
您也可以用
Object.keys
替换Object.values
const testObj = { first: [ { name: 'Den' }, { name: 'Ben' } ], second: [ { name: 'Ken'} ] } const res = Object.values(testObj).flatMap(val => val.map(el => el.name)) console.log(res)
If you can't use flatMap
, you can flatten the array using Array.prototype.concat
:如果不能使用
flatMap
,可以使用Array.prototype.concat
展平数组:
const testObj = { first: [ { name: 'Den' }, { name: 'Ben' } ], second: [ { name: 'Ken'} ] } const res = [].concat.apply([], Object.values(testObj).map(val => val.map(el => el.name))); console.log(res)
This looks efficient...这看起来很有效...
const testObj = {
first: [ { name: 'Den' }, { name: 'Ben' } ],
second: [ { name: 'Ken'} ]
}
let sol = [];
Object.values(testObj).forEach( list => list.forEach( el => sol.push(el.name)))
console.log(sol);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.