0

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??

5
  • 1
    there's no insulin key in your object Commented Apr 5, 2017 at 14:41
  • Check the path again! This rx.insulin.vials[0].total_units will throw an error if called on the object you provided! Commented Apr 5, 2017 at 14:41
  • 2
    strength and pkg_size are both undefined Commented Apr 5, 2017 at 14:42
  • That was a typo. Even if I correct the path to $( "#demo" ).html( rx.vials[0].total_units ); I still don't get what I need. Commented Apr 5, 2017 at 15:13
  • Where do trength * pkg_size come from? If there is a problem it's in them! Commented Apr 5, 2017 at 15:16

3 Answers 3

1

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

Sign up to request clarification or add additional context in comments.

Comments

1

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.

1 Comment

So something like $( "#demo" ).html( rx.vials[0].strength * rx.vials[0].pkg_size ); ?
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.