0

I have two JSON strings that are constructed dynamically. The first one is created from an XML Document:

if (window.DOMParser) {
        parser = new DOMParser();
        xmlDoc = parser.parseFromString(xml_string, "text/xml");
    } else// Internet Explorer
    {
        xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
        xmlDoc.async = false;
        xmlDoc.loadXML(xml_string);
    }
var json_str = xml2json(xmlDoc,"")

The other one created on the spot from user input.

Both have the same structure. The first one is:

{"Movies": { "Movie": [{"Title":"Movie1","Year":"2013"}]}};

and the second one is:

{"Movies": { "Movie": [{"Title":"Movie2","Year":"2014"}]}};

How can I concatenate these two so the result is two 'Movie' inside a "Movies": The result should be:

{"Movies": { "Movie": [{"Title":"Movie1","Year":"2013"},{"Title":"Movie2","Year":"2014"}]}};

I know that one method is to push {"Title":"Movie2","Year":"2014"} into ["Movies"]["Movie"] ... but is there any other way?

Ali.B
  • 307
  • 4
  • 15
  • Possible duplicate of: http://stackoverflow.com/questions/10384845/merge-two-json-objects-in-to-one-object – Miguel Jiménez Jan 28 '14 at 21:35
  • You could use Underscorejs's pluck function (http://underscorejs.org/#pluck) to pluck out all title's. – xspydr Jan 28 '14 at 21:37
  • possible duplicate of [Merge two json objects with jquery](http://stackoverflow.com/questions/8478260/merge-two-json-objects-with-jquery) – Bergi Jan 28 '14 at 22:45

2 Answers2

0

Something like the concat method?

var a = {"Movies": { "Movie": [{"Title":"Movie1","Year":"2013"}]}};
var b = {"Movies": { "Movie": [{"Title":"Movie2","Year":"2014"}]}};

var c = {"Movies": { "Movie": a.Movies.Movie.concat(b.Movies.Movie) }};
console.log(c);
Carl
  • 1,816
  • 13
  • 17
  • Damn. Beat me to it ;) Here's a jsfiddle which looks awfully similar to the answer above http://jsfiddle.net/Fresh/ZLHQF/ – Ben Smith Jan 28 '14 at 21:59
0

So this is how I achieved what I wanted ... I guess the concat method would work too:

json_obj = JSON.parse(sessionStorage.getItem('object')); //->Creating JSON object from string format

var new_item = {"Vendor":'GUY', "Title": '...', "Year":'...'};

json_obj["Movies"]["Movie"].push(new_item);

JSON.stringify(json_obj) //-> String format
Ali.B
  • 307
  • 4
  • 15