javascript - Add new attribute dynamically to the existing JSON array in Node -


I need to add an attribute that is not present in the current JSON. Jason object looks down

  var jsonObj = {"Result": "Ok", "Data": []};   

And I want to add the temperature inside the 'data', I can do it like the following.

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

And then, I want to add 'work' inside 'home', 'temperature', the result will be as below.

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

How can I do this? I was successful in incorporating 'temperature' inside the 'data', but 'home' and 'inside temperature' can be more inside the work temperature, so it should be attached to {}.

How about this?

  var temperature = {temperature: {home: 24, work: 20}}; JsonObj.data.push (temperature);   

I can not tell that it is doing it in two stages, it is important how your question is structured, but you add home and work properties In the array, like this:

  jsonObj.data.push ({temperature: {}}); jsonObj.data [0] .temperature.home = 24; JsonObj.data [0]. temperature.work = 20;   

But, this is not a good idea because it depends on the array index to find the temperature object. If this is a necessity, it would be better to do something like loop through the data array to find the object.

Edit:

An example of a loop to find the temperature object would be:

 for  (var i = 0; I & lt; jsonObj.data.length; i ++) {if (json obje .data [i]. Temperature) {break; }} JsonObj.data [i] .temperature.home = 24; jsonObj.data [i] .temperature.work = 20; Edit:  

If you are interested in a particular property then unknown at the time of development, you can use bracket syntax to isolate it. Are:

ex> for (var i = 0; i & lt; jsonObj.data.length; i ++) {if (json objetta [i] ['temperature']) {Break; }} JsonObj.data [i] ['temperature']. Home = 24; JsonObj.data [i] ['temperature']. Work = 20;

Which means you can use a variable instead of hard coding:

  var target = 'temperature'; (Var i = 0; i & lt; jsonObj.data.length; i ++) {if (json objetta [i] [goal]) {break; }} JsonObj.data [i] [goal] .home = 24; jsonObj.data [i] [goal] .work = 20;    

Comments

Popular posts from this blog

Verilog Error: output or inout port "Q" must be connected to a structural net expression -

jasper reports - How to center align barcode using jasperreports and barcode4j -

c# - ASP.NET MVC - Attaching an entity of type 'MODELNAME' failed because another entity of the same type already has the same primary key value -