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 {}.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With