Home > Enterprise >  How to get the values from a nested array?
How to get the values from a nested array?

Time:01-29

I have an array in Angular called testUsers with the following sample data:

this.testUsers = [
    {email: '[email protected]', name: 'A Smith'}
    {email: '[email protected]', name: 'B Johnson'}
    {email: '[email protected]', name: 'C Dobbs', colours: 
      ['green', 'blue', red']
    }
    {email: '[email protected]', name: 'D Mew', colours: 
      ['black', 'blue']
    }
]

What I need is to get the values inside the nested 'colours' array in a new array. Best I can get is to end up with a value as [Array(1)] which then contains data. But I need the values, not the values as an array.

How do I fix this function?

this.newArray = this.testUsers.map(value => {
  return value.colours
});

CodePudding user response:

You could take a flat array as result with a default value for not given property.

const
    testUsers = [{ email: '[email protected]', name: 'A Smith' }, { email: '[email protected]', name: 'B Johnson' }, { email: '[email protected]', name: 'C Dobbs', colours: ['green', 'blue', 'red'] }, { email: '[email protected]', name: 'D Mew', colours: ['black', 'blue'] }],
    colours = testUsers.flatMap(({ colours = [] }) => colours);

console.log(colours);

CodePudding user response:

const val1 = this.testUsers.map((value) => value.colours) // [undefined, undefined, ['green', 'blue', red'], ['black', 'blue']]
const val2 = val1.filter((val) => val !== undefined) // [['green', 'blue', red'], ['black', 'blue']]
const output = val2.flatMap(val => val) // ['green', 'blue', red', 'black', 'blue']
  • Related