动态地添加新的属性节点中现有的JSON数组 [英] Add new attribute dynamically to the existing JSON array in Node

查看:117
本文介绍了动态地添加新的属性节点中现有的JSON数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要添加不在当前的JSON存在的属性。 JSON对象看上去象下面这样。

I need to add an attribute which doesn't exist in the current JSON. The json object looks like below.

var jsonObj = {
        "result" : "OK",
        "data" : []
    };

和我想补充箱内温度数据。我能做到像下面。

And I want to add temperature inside 'data'. I could do it like below.

jsonObj.data.push( {temperature : {}} );

然后,我想补充的'家',里面的温度工作。其结果将是如下图所示。

And then, I want to add 'home', 'work' inside 'temperature'. The result would be like below.

{
    "result" : "OK",
    "data" : [
        { "temperature" : {
            "home" : 24,
            "work" : 20 } }
    ]
};

我怎么能这样做呢?我成功地插入内部数据温度,但不能加'家'和;箱内温度工作。可以有更多的温度内,因此需要与被包围{}。

How could I do this? I succeeded to insert 'temperature' inside 'data', but couldn't add 'home' & 'work' inside temperature. There could be more inside the 'temperature' so it needs to be enclosed with {}.

推荐答案

这个怎么样?

var temperature = { temperature: { home: 24, work: 20 }};

jsonObj.data.push(temperature);

我不知道,如果在两个步骤做是你的问题是如何构成的重要,但是你的可能的后来被索引到数组,这样增加家庭和工作性质:

I can't tell if doing it in two steps is important by how your question is structured, but you could add the home and work properties later by indexing into the array, like this:

jsonObj.data.push({ temperature: { }});

jsonObj.data[0].temperature.home = 24;
jsonObj.data[0].temperature.work = 20;

不过,既然它依赖于数组索引来查找温度对象不是一个好主意。如果这是一个要求,那将是更好的做这样的事情通过数据环阵列找对象你感兴趣的决定性。

But, that's not a great idea since it depends on the array index to find the temperature object. If that's a requirement, it would be better to do something like loop through the data array to find the object you're interested in conclusively.

编辑:

循环通过定位温度对象会去像这样的一个例子:

An example of looping through to locate the temperature object would go something like this:

for (var i = 0; i < jsonObj.data.length; i++) { 
  if (jsonObj.data[i].temperature) { 
    break;
  }
}

jsonObj.data[i].temperature.home = 24;
jsonObj.data[i].temperature.work = 20;

编辑:

如果它特定的属性,你会感兴趣的是,在开发时未知的,你可以用括号语法改变是:

If which particular property you'll be interested in is unknown at development time, you can use bracket syntax to vary that:

for (var i = 0; i < jsonObj.data.length; i++) { 
  if (jsonObj.data[i]['temperature']) { 
    break;
  }
}

jsonObj.data[i]['temperature'].home = 24;
jsonObj.data[i]['temperature'].work = 20;    

这意味着你可以使用一个变量出现而不是硬编码是:

Which means you could use a variable there instead of hard coding it:

var target = 'temperature';

for (var i = 0; i < jsonObj.data.length; i++) { 
  if (jsonObj.data[i][target]) { 
    break;
  }
}

jsonObj.data[i][target].home = 24;
jsonObj.data[i][target].work = 20;

这篇关于动态地添加新的属性节点中现有的JSON数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆