This question has already been answered:

I need to fill the basket object with the goods objects and sum the basket cost with its method.

I did this:

let basket = { sumBasket: function() { let sum = 0; for(var prop in this) { if(prop != "sumBasket") { sum = sum + prop.count * prop.price; } } return sum; } }; let smartphone = { price: 320, count: 2 }; let refrigerator = { price: 840, count: 1 }; let television = { price: 550, count: 3 }; function addToBasket(items) { return (basket = { ...basket, ...items }); }; addToBasket({smartphone, refrigerator, television}); console.log(basket); basket.sumBasket(); console.log(basket.sum); 

But my sum is NaN , since prop.count and prop.price are undefined

I guess I do not correctly refer to the properties of the goods. Help as needed?

Reported as a duplicate at Grundy. javascript 16 Sep '18 at 15:24

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

  • I need to understand not only the properties, namely to make a basket, and I have already received the correct answer - Valeriy Petukhov

1 answer 1

  1. You access the sum property in console.log(basket.sum); but you do not have this property in the object therefore undefined .

  2. props in for(var prop in this) is only the key to the object, not the object itself. prop.count also undefined . To get the object you need this[props]

Here are my suggestions

 const basket = { sum: 0, // свойство, чтоб было к чему обращаться goods: {}, // cоздайте отдельное свойство где будут лежать товары sumBasket: function () { let sum = 0; for (var key in this.goods) { const elem = this.goods[key]; // получить товар по ключу sum += elem.count * elem.price; } this.sum = sum; // запись свойста return sum; } }; const smartphone = { price: 320, count: 2 }; const refrigerator = { price: 840, count: 1 }; const television = { price: 550, count: 3 }; basket.goods = { smartphone, refrigerator, television }; basket.sumBasket(); console.log(basket.sum);