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