简体   繁体   English

如何将键中包含 arrays 的 object 转换为具有特定字段的字符串数组?

[英]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而不是分别调用mapflat 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.

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