且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

动态地添加新的属性节点中现有的JSON数组

更新时间:2023-09-06 22:10:16

这个怎么样?

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;