0

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)
2
  • what is the problem with your solution? Commented Aug 12, 2022 at 11:37
  • I don't want to use flat, flatMap Commented Aug 12, 2022 at 11:38

2 Answers 2

1

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)

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.