2011-09-24 23 views
1

創造一個新領域我有一個JavaScript對象,它是這樣的:修改JSON對象通過使用現有的元素

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

如何創建一個使用重量叫BMI新場/(身高)^ 2這樣的新對象變爲:

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

回答

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。如果您不需要複製對象,請查看代碼的註釋部分。

+0

需要注意的是這不會產生一個新的對象很重要,它會修改原始一個就地具有原始對象的副本。 –

+0

我看到..謝謝你這個很好的解決方案:) –

+0

不錯的使用推+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> 
+0

哇,全面:) –

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) ; 
} 
+0

短而甜:) –