Home > database >  How to get data from an array inside an object (JavaScript)
How to get data from an array inside an object (JavaScript)

Time:09-13

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) {
    
    }

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

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 => conutries[key].cities)

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