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
- Modifying a JSON object by creating a New Field using existing Elements
- js:Creating a new object
- Creating and Using a COM Object by Using Visual Studio 2005
- Creating a Security Descriptor for a New Object in C++
- Creating a New Project
- Creating a new application
- Creating a List Item instance programmatically using the object model
- Creating a New ASM Disk Header After Existing One Is Corrupted
- PDB创建之Creating a PDB by Cloning an Existing PDB or Non-CDB
- Creating a new Microsoft Word document from a template using OpenXml
- Creating a New Window Group
- CREATING A NEW CONTENT PROVIDER
- Creating a new Storm project
- Creating a Generic Object Factory
- post a json object with an array using curl
- Creating an array of floats using new-object
- Creating a Chm build using Sandcastle
- Creating a Simple BSP Application Using AJAX
- Centos一键升级PHP到最新版,如php5.3,php5.4
- 大半夜不睡觉瞎胡闹
- cocoa 自动键值观察(KVO)--笔录
- How do I add a tool tip to a span element?
- [JAVA] 定义函数时功能的细分;
- Modifying a JSON object by creating a New Field using existing Elements
- Lua 中实现面向对象
- vps httpd 多个站点配置
- Windows XP操作系统激活完全手册
- Linux 学习笔记1
- JBOSS EAP 6 系列五 EJB客户端 —去掉jboss-ejb-client配置文件
- Convert between JSON and String in Javascript
- JSON.stringify 语法讲解
- Power up Angular's $http service with caching