Nitesh Singh
Nitesh Singh

Reputation: 395

How to get data from nested objects in the form of array

As you can see, the keys are now the name of the items and the corresponding value is another object consisting of two keys - quantity and price.

    var itemsToBuy = {
    milk: {
        quantity : 5,
        price: 20
    },
    bread: {
        quantity : 2,
        price: 15
    },
    potato: {
        quantity : 3,
        price: 10
    }
}

I tried but I am getting only undefined output. Want to get data such like :

['milk', 'bread', 'potato']

[20, 15, 10]

Upvotes: 6

Views: 5594

Answers (4)

Aalexander
Aalexander

Reputation: 5004

Solution

  • With Object.keys() you can get the keys of your Object as an array. -> ['milk', 'bread', 'potato']

  • With Object.entries() in combination with map() you can get the values of the price property as an array. -> [20, 15, 10]

Example:

     var itemsToBuy = {
        milk: {
            quantity : 5,
            price: 20
        },
        bread: {
            quantity : 2,
            price: 15
        },
        potato: {
            quantity : 3,
            price: 10
        }
    }
    const keys = Object.keys(itemsToBuy);
    const val = Object.entries(itemsToBuy).map((element)=> element[1].price)

    console.log(keys);
    console.log(val);
    

Upvotes: 3

kasia
kasia

Reputation: 298

To get object keys you can use: Object.keys()

let keys = Object.keys(itemsToBuy) // ["milk", "bread", "potato"]

And for the nested values you can get 1st all values

let values = Object.values(itemsToBuy) // [{quantity : 5, price: 20}, {quantity : 2, price: 15}, {quantity : 3, price: 10}]

And then map to return the new array with elements you want to extract ex.price:

let price = values.map(value => value.price) // [20, 15, 10]

Upvotes: 2

Sonia Aguilar
Sonia Aguilar

Reputation: 171

for names:

Object.keys(itemsToBuy) //["milk", "bread", "potato"]

and for prices:

Object.entries(itemsToBuy).map((el)=> el[1].price)//[20, 15, 10]

Upvotes: 2

MUHAMMAD ILYAS
MUHAMMAD ILYAS

Reputation: 1450

const object1  = {
  milk: {
      quantity : 5,
      price: 20
  },
  bread: {
      quantity : 2,
      price: 15
  },
  potato: {
      quantity : 3,
      price: 10
  }
}
console.log(Object.entries(object1).map(([key,value])=> value.price))

Upvotes: 5

Related Questions