1

I have some json strings that look like that:

var TheJson = "{Key:[array of objects]}"

Key is actually a date and the json contains arrays of objects. I want to add this object to another object HistoryOfData, sort of like the .push method on arrays. Basically, I want the HistoryOfData object to have key value nested objects where the keys are dates and the values are arrays of data.

How do I push an object into another object?

2
  • The JSON string would have to be parsed into a real Object first. (see JSON.parse). Commented Jun 11, 2012 at 18:46
  • @JamesMcLaughlin: indeed, but once I have the object from json, how do I push it to HistoryOfData? Commented Jun 11, 2012 at 18:49

2 Answers 2

1

Just set them in the new object. Example:

var json1 = '{"06/08/2012": [{}, {"x": 1}, {"y": 2}, {"x": 3, "y": 4}]}';
var json2 = '{"06/10/2012": [{}, {"x": 5}, {"y": 6}, {"x": 7, "y": 8}]}';
var new_obj = {}, temp;

temp = JSON.parse(json1);
for(key in temp)
    new_obj[key] = temp[key];

var temp = JSON.parse(json2);
for(key in temp)
    new_obj[key] = temp[key];

console.log(new_obj); // Has two keys, each key is a date 
                      // and the values are Arrays of objects
Sign up to request clarification or add additional context in comments.

Comments

0
for(var key in JSON.parse(TheJson)) {
  HistoryOfData[key] = TheJson[key]
}

JSON.parse is needed if TheJson is really still a String, and hasn't yet been turned into a JS Object.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.