6

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]
0

4 Answers 4

5

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

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

Comments

3

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

Comments

2

for names:

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

and for prices:

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

Comments

2

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]

Comments

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.