Answer the question
In order to leave comments, you need to log in
How to count number in json file?
var myObject = {
"items": {
"1": {
"SIMPLE_BASKET_TITLE": "Привет, мир!",
"SIMPLE_BASKET_QUO": 3,
"SIMPLE_BASKET_PRICE": 0,
"SIMPLE_BASKET_CATEGORY": "Без рубрики"
},
"4": {
"SIMPLE_BASKET_TITLE": "Смартфон Microsoft Lumia 640",
"SIMPLE_BASKET_QUO": "29",
"SIMPLE_BASKET_PRICE": 10000,
"SIMPLE_BASKET_CATEGORY": "Каталог"
},
"6": {
"SIMPLE_BASKET_TITLE": "Силиконовый чехол для Lumia 640",
"SIMPLE_BASKET_QUO": 5,
"SIMPLE_BASKET_PRICE": 100,
"SIMPLE_BASKET_CATEGORY": "Каталог"
}
},
"userName": "admin",
"userEmail": "[email protected]",
"userPhone": "",
"userComment": "",
"errorMessages": []
};
Answer the question
In order to leave comments, you need to log in
var total = Object.keys(myObject.items).reduce( (total, key) => {
var item = myObject.items[key];
total.q += item.SIMPLE_BASKET_QUO | 0;
total.a += item.SIMPLE_BASKET_QUO * item.SIMPLE_BASKET_PRICE;
return total;
}, { q: 0, a: 0 } );
console.log(total);
If you are only interested in the quantity and the "item" object is unchanged, then like this:
If you are interested in some more complex logic, then, for example, like this:
var fullCost = 0;
for (itemIndex in myObject.items) {
var item = myObject.items[itemIndex];
var quantity = (typeof item.SIMPLE_BASKET_QUO !== 'undefined' ? Number(item.SIMPLE_BASKET_QUO) : 0);
var price = (typeof item.SIMPLE_BASKET_PRICE !== 'undefined' ? Number(item.SIMPLE_BASKET_PRICE) : 0);
fullCost += quantity*price;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question