1

How can I combine two different JSON responses into one object so I can manipulate my data from a single source?

I've read different implementations, however not quite the way I have my code structured right now.

I'm pretty green on it, so if you can provide me a hands-on example that would be greatly appreciated.

ex:

$(function() {
    let hotels = 'data1.json';
    let guests = 'data2.json';
    $.getJSON(hotels)
        .then(function (res) {
            console.log(res);
        })
        .fail(function (err) {
            console.log(err);
        });
    $.getJSON(guests)
        .then(function (res) {
            console.log(res);
        })
        .fail(function (err) {
            console.log(err);
        });

      /*** start logic for application here ***/  

    let newObject = //How can I combine both responses above???
    console.log(newObject);


});

Bellow the responses that I get from each request: enter image description here

3
  • you want this in one array ? Commented Sep 30, 2017 at 18:55
  • 1
    what do you mean by "combine" in one object? Commented Sep 30, 2017 at 18:55
  • Have both responses saved into a new object. So can manipulate it having all data in one place. Commented Sep 30, 2017 at 18:57

1 Answer 1

6

You can do a Promise.all chain to get the both results in a new object.

Promise.all([$.getJSON(hotels), $.getJSON(guests)])
  .then( results => {
    console.log(results);
  });

Example: https://repl.it/Ls2c/1

Sign up to request clarification or add additional context in comments.

8 Comments

Baruch, this is already a huge step and thank you. Right now results logs [Array(5), Array(6)], Could we concatenate the arrays? @Baruch
Please note that the Promise.all waits for the resolution of all the promises or the first that is rejected.
You can also destructure like this: .then(([hotels, guests]) => console.log({hotels, guests})). To concatenate them, just use results[0].concat(results[1]).
Thank you very much @Xufox and Baruch !!
@Xufox if I were to use your destructuring suggestion, Would your .then example replace .then(results => { ..... ?
|

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.