我有一个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"
}
如何使用权重/(高度)^ 2创建一个名为BMI的新字段,以便新对象变为:
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"
}
答案 0 :(得分:5)
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;
}
初始化new_obj
后,循环遍历数组obj.data
。计算BMI,并将所有属性的副本添加到new_obj
。如果您不必复制对象,请查看代码的注释部分。
答案 1 :(得分:2)
尝试使用此代码,在下面的代码中我使用相同的对象添加一个字段。我们还可以通过将现有对象复制到临时变量
来复制原始对象<!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>
答案 2 :(得分:1)
var data = obj['data'];
for( var i in data )
{
var person = data[i];
person.BMI = (person.weight/ Math.pow(person.height, 2)).toFixed(2) ;
}