Search code examples
javascriptunderscore.jslodash

Flatten array with parent values


Given

[
 {"id":1,"country":"US","area":1,"values":[{"city":"Chicago"},{"city":"New York"}]}, 
 {"id":2,"country":"Canada","area":2,"values":[{"city":"Toronto"},{"city":"Quebec"}]}
]

I'm trying to flatten the data to table format with each object in the values array as a table row with the parents fields duplicated.

Result

[
  {"country":"US","city":"Chicago"},
  {"country":"US","city":"New York"},
  {"country":"Canada","city":"Toronto"},
  {"country":"Canada","city":"Quebec"}
]

I would like to mention what fields to keep from parent fields. For ex single field i.e country field in our example. Other examples could include multiple or all parent fields.

Is there a elegant way to achieve the expected results ? Right now I'm using nested for loops to achieve the same.


Solution

  • It ends up being two nested loops, but you can take advantage of map and reduce to simplify the code. See below:

    const input = [
     {"id":1,"country":"US","area":1,"values":[{"city":"Chicago"},{"city":"New York"}]}, 
     {"id":2,"country":"Canada","area":2,"values":[{"city":"Toronto"},{"city":"Quebec"}]}
    ];
    
    const result = input.reduce((output, {country, values}) =>
      output.concat(values.map(({city}) => ({ country, city }))), []);
      
    console.log(result);