0

I'm trying get data from array so that look like this:

[Rome, Milan, Barselona, Madrid]

and my brain seems like go to blackout... How can i do this?

const countries = {
        italy: {
            id: 1,
            cities: ["Rome", "Milan"],
        },
        spain: {
            id: 2,
            cities: ["Barselona", "Madrid"],
        }
    };

    function getCitiesDates(data) {
    
    }

3 Answers 3

2

Using Object#values and Array#flatMap:

function getCitiesDates(data) {
  return Object.values(data).flatMap(({ cities = [] }) => cities);
}

const countries = {
  italy: { id: 1, cities: ["Rome", "Milan"] },
  spain: { id: 2, cities: ["Barselona", "Madrid"] }
};
console.log( getCitiesDates(countries) );

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

Comments

1

You can get it in one line with Object.keys(data).flatMap(c => data[c].cities);

const countries = {
  italy: {
    id: 1,
    cities: ["Rome", "Milan"],
  },
  spain: {
    id: 2,
    cities: ["Barselona", "Madrid"],
  }
};

function getCitiesDates(data) {
  return Object.keys(data).flatMap(c => data[c].cities);
}
console.log(getCitiesDates(countries))

Comments

1

One way to solve it could be to use Object.Keys(), loop the Keys and then map the cities.

Something like this:

const keys = Object.Keys(countries);
const cities = keys.flatMap(key => countries[key].cities)

console.log(cities) // [Rome, Milan, Barselona, Madrid]

1 Comment

Object.keys() (not Keys()).

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.