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

来源:互联网 发布:戴尔公司网络品牌策划 编辑:程序博客网 时间:2024/06/15 06:50

http://stackoverflow.com/questions/7540071/modifying-a-json-object-by-creating-a-new-field-using-existing-elements

Question:

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"}
Bad Solution:

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.

Good Solution:
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 0
原创粉丝点击