简体   繁体   中英

how to get price data from 2d array in javascript?

I have json as below. what i am trying to do is calculate sum of price per each user in this case for example, user001: 91.68

where I am in stuck is I am trying to write for loop to get those data from json but I have to assign direct usernumber(eg user001) to code. I want to use that like shoppingJson[i][j] something like that

I only can get result when I write below

console.log(shoppingJson[0].user001[0].price)

how should I do to access 2d array values?

var shoppingJson = [{
    "user001": [
      {
        "productId": "123",
        "name": "Product 123",
        "price": 14.23
      },
      {
        "productId": "456",
        "name": "Product 456",
        "price": 4.56
      },
      {
        "productId": "789",
        "name": "Product 789",
        "price": 72.89
      }
    ]},{
    "user002": [
      {
        "productId": "321",
        "name": "Product 321",
        "price": 3.21
      },
      {
        "productId": "654",
        "name": "Product 654",
        "price": 61.54
      },
      {
        "productId": "987",
        "name": "Product 987",
        "price": 59.87
      }
    ]},{
    "user003": [
      {
        "productId": "777",
        "name": "Product 888",
        "price": 4.213
      },
      {
        "productId": "888",
        "name": "Product 999",
        "price": 6.24
      },
      {
        "productId": "999",
        "name": "Product 111",
        "price": 9.71
      }
    ]}
]
var price = {};
for(item of shoppingJson){
    for( user in item ){
        price[user] = 0;
        for(product of item[user]){
            price[user] += product.price;
        }
    }
}

After executing this, you will get the sums in the object price . The object price will then contain the following

{
    user001: 91.68,
    user002: 124.62,
    user003: 20.163
}
shoppingJson.forEach(function(obj) {
    var totalPrice = 0;
    for(key in obj) {
        obj[key].forEach(function(o) {
            totalPrice += o.price;
        });
    };
    console.log(totalPrice);
});

You could use a forEach loop to iterate through each of the objects within the shoppingJson array. Then you can create a variable to store the total price, and it will be initialized to zero. For each key within the object you can do another forEach iteration (because the value of that key with be the array of objects), and add the value of "price" from that object to the totalPrice variable. If you try this on the first object in the shoppingJson array you get 91.68.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM