简体   繁体   中英

JSON math on object array values

I'm trying to multiply two components together in my object array

{
  "rx": {
    "vials": [
      {
        "description": "Rx 1",
        "strength": 100,
        "form": "ML",
        "pkg_size": 10,
        "case_size": 1,
        "total_units": strength * pkg_size,
        "ndc": "12345-1234-12",
        "covered": true
      }
    ]
  }
}

But if I do something like

$( "#demo" ).html( rx.vials[0].total_units );

I get nothing or NaN

What am I doing wrong??

You can not do that. If you want to do some math inside an object you have to use external variables - you can't access object's properties from within itself.

You can try something like this :

You can add total_units property into vials[0] after doing the calculation.

 var jsonObj = { "rx": { "vials": [ { "description": "Rx 1", "strength": 100, "form": "ML", "pkg_size": 10, "case_size": 1, "ndc": "12345-1234-12", "covered": true } ] } }; jsonObj.rx.vials[0].total_units = jsonObj.rx.vials[0].strength * jsonObj.rx.vials[0].pkg_size; console.log(jsonObj.rx.vials[0].total_units); 

You can try something like this:

for (var i = 0; i < rx.vials.length; i++) {
  rx.vials[i].total_units = rx.vials[i].strength * rx.vials[i].pkg_size;
}

console.log(rx.vials[0].total_units);

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