Home > Software design >  How transform object that contain arrays in keys to array of string with certain field?
How transform object that contain arrays in keys to array of string with certain field?

Time:08-12

I just have object, that contains arrays in keys, and I need get array of string with name property. I cope to do it with flat, but probably there is better solution

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)

CodePudding user response:

You can use flatMap instead of calling map and flat separately. Also you can replace Object.keys with 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:

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)

CodePudding user response:

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);
  • Related