-1

Is anyone can help me to found this output. Sample output:

['milk', 'bread', 'potato']
[20, 15, 10]

Here is the code.

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

I have found for first array using Object.keys(itemsToBuy) but not able to found for second array.

2 Answers 2

1

User Object.values and map for second array

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

const out1 = Object.keys(itemsToBuy);
const out2 = Object.values(itemsToBuy).map(({ price }) => price);

console.log(out1, out2);

// Using for..in loop

const out3 = [];

for(const key in itemsToBuy) {
  out3.push(itemsToBuy[key].price)
}

console.log(out3)

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

Comments

0

Object.values(itemsToBuy).map(item => item.price) should do the trick

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.