Friday, May 10, 2024
 Popular · Latest · Hot · Upcoming
27
rated 0 times [  30] [ 3]  / answers: 1 / hits: 59101  / 10 Years ago, tue, april 22, 2014, 12:00:00

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 {}.


More From » json

 Answers
5

How about this?



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.



Edit:



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;


Edit:



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;

[#71363] Saturday, April 19, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kaitlynnb

Total Points: 402
Total Questions: 96
Total Answers: 109

Location: Trinidad and Tobago
Member since Fri, May 8, 2020
4 Years ago
kaitlynnb questions
;