我有一个像这样的 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"
}
如何使用 weight/(height)^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"
}
最佳答案
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
。如果您不必复制该对象,请查看代码的注释部分。
关于javascript - 通过使用现有元素创建新字段来修改 JSON 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7540071/