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?

3

2 Answers 2

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);
Sign up to request clarification or add additional context in comments.

1 Comment

Damn. Beat me to it ;) Here's a jsfiddle which looks awfully similar to the answer above jsfiddle.net/Fresh/ZLHQF
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

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.