0

I have an array of objects that have a price property, and I'm trying to sum all the prices in the object. I think what's tripping me up is that it's an array of objects so I'm having a hard time accessing the price property.

Here's what's displaying in the console: 0[object Object][object Object][object Object][object Object][object Object][object Object][object Object]

Here's my code:

const items = [
    { name: 'Bike', price: 100 },
    { name: 'TV', price: 200 },
    { name: 'Album', price: 10 },
    { name: 'Book', price: 5 },
    { name: 'Phone', price: 500 },
    { name: 'Computer', price: 1000 },
    { name: 'Keyboard', price: 25 }
];
const totalPrice = items.reduce((total, curVal) => {
    return total + curVal;
}, 0);
3
  • 2
    use total + curVal.price, since curVal is an object with a property named price - or, items.reduce((total, {price:curVal}) => { without changing the rest of the code Commented Apr 11, 2020 at 0:57
  • Is the {price:curVal} considered destructuring the object? Commented Apr 11, 2020 at 13:04
  • destructure and assigning to new variable name Commented Apr 12, 2020 at 0:01

3 Answers 3

1

You were almost there!

const items = [
    { name: 'Bike', price: 100 },
    { name: 'TV', price: 200 },
    { name: 'Album', price: 10 },
    { name: 'Book', price: 5 },
    { name: 'Phone', price: 500 },
    { name: 'Computer', price: 1000 },
    { name: 'Keyboard', price: 25 }
];
const totalPrice = items.reduce((a, b)=> a + b.price,0);
console.log(totalPrice);

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

Comments

0

Because curVal is object, you need use price property by curVal.price

const items = [
    { name: 'Bike', price: 100 },
    { name: 'TV', price: 200 },
    { name: 'Album', price: 10 },
    { name: 'Book', price: 5 },
    { name: 'Phone', price: 500 },
    { name: 'Computer', price: 1000 },
    { name: 'Keyboard', price: 25 }
];
const totalPrice = items.reduce((total, curVal) => {
    return total + curVal.price;
}, 0);

console.log(totalPrice);

Comments

0
const items = [
  { name: "Bike", price: 100 },
  { name: "TV", price: 200 },
  { name: "Album", price: 10 },
  { name: "Book", price: 5 },
  { name: "Phone", price: 500 },
  { name: "Computer", price: 1000 },
  { name: "Keyboard", price: 25 },
];

let sum = 0;
items.forEach((el) => {
  sum += el.price;
});
console.log(sum);

explanation - we set sum initially to zero then we will loop through the array using foreach and access price property using el.price and calculate the sum

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.