I have a JavaScript object array with the following structure:
const array = [
{userId: 'P282', zones: ['188']},
{userId: 'P277', zones: []},
{userId: 'P280'},
{userId: 'P281'},
{userId: 'P279'},
{userId: 'U57', zones: ['190', '189', '188']},
];
I want to map all the zones from each user to a different array which looks like
const zones = ['188', '190', '189', '188']
With or without duplicate elements
You can do a function like this with array.reduce()
const getZones = (array) => {
return array.reduce((acc, curr) => {
if (curr.zones) {
return [...acc, ...curr.zones];
}
return acc;
}, []);
}
flatMap get zones in one array.undefined with filter(Boolean)array.flatMap(x=>x.zones) // ['188', undefined, undefined, undefined, '190', '189', '188']
.filter(Boolean); // ['188', '190', '189', '188']
When learning, you should use a simple for loop.
With the spread operator (...) you can break an array into individual components.
Use a combination of both to get the zones :
const array = [
{userId: 'P282', zones: ['188']},
{userId: 'P277', zones: []},
{userId: 'P280'},
{userId: 'P281'},
{userId: 'P279'},
{userId: 'U57', zones: ['190', '189', '188']},
];
let zones = [];
for(let i = 0 ; i < array.length;i++){
if(Array.isArray(array[i].zones))
zones = [...zones,...array[i].zones];
}
console.log(zones);