Home > Enterprise >  Map items in a property within an object array
Map items in a property within an object array

Time:09-30

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

CodePudding user response:

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;
    }, []);
}

CodePudding user response:

Array.reduce is the best way for your case.

const array = [{
    userId: 'P282',
    zones: ['188']
  },
  {
    userId: 'P277',
    zones: []
  },
  {
    userId: 'P280'
  },
  {
    userId: 'P281'
  },
  {
    userId: 'P279'
  },
  {
    userId: 'U57',
    zones: ['190', '189', '188']
  },
];

const result = array.reduce((acc, item) => {
   return acc.concat(item.zones ?? []);
}, []);

console.log(result);

CodePudding user response:

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

  • Related