0

I have an array like that :

[{
        "id": 1,
        "city": [{
                "name": "BERLIN",
            }
        ],
    }, {
        "id": 2,
        "city": [{
                "name": "PARIS",
            }
        ],
    }, {
        "id": 3,
        "city": [{
                "name": "LONDON",
            }, {
                "name": "EXETER",
            }
        ],
    }

And I would like extract the values below :

[
    {id: 1, city: {name: "BERLIN"}, 
    {id: 2, city: {name: "PARIS"},
    {id: 3, city: {name: "LONDON"},
    {id: 3, city: {name: "EXETER"} 
]

I tried with and two map but, I don't have the result expected.

Can you help me for this issue.

Thank you.

Heptagram
  • 105
  • 1
  • 9

1 Answers1

3

You can use flatMap() for this:

const a = [{
  "id": 1,
  "city": [{
    "name": "BERLIN",
  }],
}, {
  "id": 2,
  "city": [{
    "name": "PARIS",
  }],
}, {
  "id": 3,
  "city": [{
    "name": "LONDON",
  }, {
    "name": "EXETER",
  }],
}];

const result = a.flatMap(({id, city}) => city.map(c => ({id, city: c})));

console.log(result);
Robby Cornelissen
  • 91,784
  • 22
  • 134
  • 156