Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get the values from a nested array?

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

this.testUsers = [
    {email: '1@fake.com', name: 'A Smith'}
    {email: '2@fake.com', name: 'B Johnson'}
    {email: '3@fake.com', name: 'C Dobbs', colours: 
      ['green', 'blue', red']
    }
    {email: '4@fake.com', 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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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

const
    testUsers = [{ email: '1@fake.com', name: 'A Smith' }, { email: '2@fake.com', name: 'B Johnson' }, { email: '3@fake.com', name: 'C Dobbs', colours: ['green', 'blue', 'red'] }, { email: '4@fake.com', name: 'D Mew', colours: ['black', 'blue'] }],
    colours = testUsers.flatMap(({ colours = [] }) => colours);

console.log(colours);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading