开发者

Modifying a JSON object by creating a New Field using existing Elements

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"
}


var persons = obj.data;
var new_obj = {data: [], school: obj.school};
for(var i=0; i<persons.length; i++){
    var person = persons[i];
    new_obj.data.push({
        name: person.name,
        height: person.height,
        weight: person.weight,
        BMI: Math.round(person.weight / Math.pow(person.height, 2)*10)/10;
    });
    /* Use the next line if you don't want to create a new object,
       but extend the current object:*/
    //persons.BMI = Math.round(person.weight / Math.pow(person.height, 2)*10)/10;
}

After new_obj is initialised, a loop walks through array obj.data. The BMI is calculated, and added along with a copy of all properties to new_obj. If you don't have to copy the object, have a look at the commented part of the code.


Try with this code, in this below code I used same object to add one more field. We can also have copy of the original object by copying existing one to temp variable

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
    <title>Modifying a JSON object by creating a New Field using existing Elements</title>
</head>
<body>
<h2>Modifying a JSON object by creating a New Field using existing Elements</h2>
<script type="text/javascript">
    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"
    }
    alert(obj.data[0].weight);

    var temp=obj["data"];
    for (var x in temp) {
        var w=temp[x]["weight"];
        var h=temp[x]["height"];
        temp[x]["BMI"] = (w / (h) ^ 2) ;

    }

    alert(obj.data[1].BMI);
</script>
</body>
</html>


var data = obj['data'];
for( var i in data ) 
{
   var person = data[i]; 
   person.BMI = (person.weight/ Math.pow(person.height, 2)).toFixed(2) ;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜