-1

I have the following object structure:

regions: [
  {
    name: reg1, 
    subregions: [
      {name: subreg11},
      {name: subreg12}
    ]
  },
  {
    name: reg2, 
    subregions: [
      {name: subreg21},
      {name: subreg22}
    ]
  }
]

What I'd like, is to extract an array of the subregions, like so:

[{name: subreg11}, {name: subreg12}, {name: subreg21}, {name: subreg22}]

...and I'd like to do that with a one-line array.prototype-function, like .filter, .map, .forEach etc.

I've managed to do it in three lines like this (including the return-statement, which I'd like to have in the one-liner):

let subregions = []
regions.forEach(reg => reg.subregions.forEach(subregion => subregions.push(subregion)))
return locs

Does anyone know how I could do this?

EDIT July 2020: I see the question has been marked as a duplicate by @nina-sholz, but I don't believe this is true. The linked question asks "Why no Array.prototype.flatMap in javascript?", while my question was a description of a way to solve a problem. I didn't request the flatMap function specifically, and marking this as a duplicate simply says "you should have intuitively known that Array.prototype.flatMap was the thing you were looking for".

Sebastian
  • 1,321
  • 9
  • 21

2 Answers2

2

flatMap and extract the subregions property:

const regions = [
  {
    name: 'reg1',
    subregions: [
      {name: 'subreg11'},
      {name: 'subreg12'}
    ]
  },
  {
    name: 'reg2', 
    subregions: [
      {name: 'subreg21'},
      {name: 'subreg22'}
    ]
  }
];

const output = regions.flatMap(({ subregions }) => subregions);
console.log(output);

You can also use reduce:

const regions = [
  {
    name: 'reg1',
    subregions: [
      {name: 'subreg11'},
      {name: 'subreg12'}
    ]
  },
  {
    name: 'reg2', 
    subregions: [
      {name: 'subreg21'},
      {name: 'subreg22'}
    ]
  }
];

const output = regions.reduce((a, { subregions }) => a.concat(subregions), []);
console.log(output);

Pretty much any Javascript code can be reduced into a single line, but it won't necessarily be readable.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
1

You can use map and flat

const regions = [{name: 'reg1',subregions: [{name: 'subreg11'},{name: 'subreg12'}]},{name: 'reg2', subregions: [{name: 'subreg21'},{name: 'subreg22'}]}];
const output = regions.map(({ subregions }) => subregions).flat();
console.log(output);
Code Maniac
  • 37,143
  • 5
  • 39
  • 60