Home > Blockchain >  How to get values of child objects in an array of objects in javascript
How to get values of child objects in an array of objects in javascript

Time:11-08

states = [{
    name: telangana,
    cities: [{
      id: 1,
      name: foo
    }, {
      id: 2,
      name: joo
    }, {
      id: 3,
      name: goo
    }]
  },
  {
    name: punjab,
    cities: [{
      id: 4,
      name: tyu
    }, {
      id: 5,
      name: ery
    }, {
      id: 6,
      name: doo
    }]
  },
  {
    name: mumbai,
    cities: [{
      id: 7,
      name: eee
    }, {
      id: 8,
      name: qqq
    }, {
      id: 9,
      name: www
    }]
  },
]

I want response like [foo, joo, goo, tyu, ery,doo, eee,qqq,www]

Can someone help me ?

CodePudding user response:

const getNames = (data) => {
 const nameArr = [];
 data.forEach((ele) => {
  ele.cities.forEach((ele2) => {
   nameArr.push(ele2.name);
  })
 })
 return nameArr;
}
getNames(states);

Try this please!

CodePudding user response:

states = [{
    name: "telangana",
    cities: [{
      id: 1,
      name: "foo"
    }, {
      id: 2,
      name: "joo"
    }, {
      id: 3,
      name: "goo"
    }]
  },
  {
    name: "punjab",
    cities: [{
      id: 4,
      name: "tyu"
    }, {
      id: 5,
      name: "ery"
    }, {
      id: 6,
      name: "doo"
    }]
  },
  {
    name: "mumbai",
    cities: [{
      id: 7,
      name: "eee"
    }, {
      id: 8,
      name: "qqq"
    }, {
      id: 9,
      name: "www"
    }]
  },
]

const wantedArray = []

for(i=0; i < states.length; i  ){
    for(j=0; j < states[i].cities.length; j  ){
    wantedArray.push(states[i].cities[j].name)
  }
}

console.log(wantedArray)

Just give it an empty array, then you loop through the states indexes, each index in states will have a cities array, then you just need to loop it again in that array to get each name of the cities. From then, you are using the push method that Javascript provides to push it to the empty array.

Here's how I'm doing it in JSFiddle, there will have a better way to do this, too.

CodePudding user response:

Just write one line:

Learn more about reduce() and map()

const states = [{ name: "telangana", cities: [{ id: 1, name: "foo" }, { id: 2, name: "joo" }, { id: 3, name: "goo" }] }, { name: "punjab", cities: [{ id: 4, name: "tyu" }, { id: 5, name: "ery" }, { id: 6, name: "doo" }] }, { name: "mumbai", cities: [{ id: 7, name: "eee" }, { id: 8, name: "qqq" }, { id: 9, name: "www" }] }, ];

const result = states.reduce((acc, { cities }) => [...acc, ...cities.map(({ name }) => name)], []);
console.log(result);

  • Related