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".