I
I
Igor Fedorov2016-07-10 15:28:49
JavaScript
Igor Fedorov, 2016-07-10 15:28:49

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": []
};

There is such a thing. How can you count all "SIMPLE_BASKET_QUO" and "SIMPLE_BASKET_PRICE" if the number of items can be anything. Thanks in advance to everyone for the answer

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
surefire, 2016-07-10
@surefire

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

I
Immortal_pony, 2016-07-10
@Immortal_pony

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 question

Ask a Question

731 491 924 answers to any question