I have a javascript object that goes like this:
var obj = {"data":
[
{"name":"Alan","height":1.71,"weight":66},
{"name":"Ben","height":1.82,"weight":90},
{"name":"Chris","height":1.63,"weight":71}
]
,"school":"Dover Secondary"
}
How do I create a new field called BMI using weight/(height)^2 such that the new object becomes:
var new_obj = {"data":
[
{"name":"Alan","height":1.71,"weight":66,"BMI":22.6},
{"name":"Ben","height":1.82,"weight":90,"BMI":27.2},
{"name":"Chris","height":1.63,"weight":71,"BMI":26.7}
]
,"school":"Dover Secondary"
}
After
new_objis initialised, a loop walks through arrayobj.data. The BMI is calculated, and added along with a copy of all properties tonew_obj. If you don’t have to copy the object, have a look at the commented part of the code.