【问题标题】:Modifying a JSON object by creating a New Field using existing Elements通过使用现有元素创建新字段来修改 JSON 对象
【发布时间】:2011-09-24 15:53:11
【问题描述】:

我有一个像这样的 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"
}

【问题讨论】:

    标签: javascript


    【解决方案1】:
    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。如果您不必复制对象,请查看代码的注释部分。

    【讨论】:

    • 重要的是要注意,这不会创建新对象,它会就地修改原始对象。
    • 我明白了.. 感谢您提供这个不错的解决方案 :)
    • 别忘了将BMI四舍五入到小数点后两位:-P
    【解决方案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>
    

    【讨论】:

      【解决方案3】:
      var data = obj['data'];
      for( var i in data ) 
      {
         var person = data[i]; 
         person.BMI = (person.weight/ Math.pow(person.height, 2)).toFixed(2) ;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-12-24
        • 2015-03-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-08-03
        相关资源
        最近更新 更多