Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

75
Views
Map items in a property within an object array

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

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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;
    }, []);
}
about 4 years ago · Juan Pablo Isaza Report

0

  • flatMap get zones in one array.
  • remove undefined with filter(Boolean)
array.flatMap(x=>x.zones) // ['188', undefined, undefined, undefined, '190', '189', '188']
.filter(Boolean); // ['188', '190', '189', '188']
about 4 years ago · Juan Pablo Isaza Report

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!