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.

1
  • @RobbyCornelissen: sorry, mistake of me, I fixed Commented Mar 15, 2021 at 23:55

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

2 Comments

Sorry, but I don't have flatmap in my angular project...
See here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.