Mr.Turtle
Mr.Turtle

Reputation: 3090

Merge X-numbers of JSON into one JavaScript Object

I have several Ajax-requests that retrieves data from the server... I want to add them together, so I can use the data set later.

This is how one JSON-looks like:

{
   "51" : { id:"51", name:"frank" },
   "52" : { id:"52", name:"jonny" }
}

A second later there might come another one, with the exactly the same structure. How do I just "append" a new json into this to make a large object with the same structure..

EG: (append like this)

{
   "51" : { id:"51", name:"frank" },
   "52" : { id:"52", name:"jonny" },
   "72" : { id:"72", name:"daniel"},
   "73" : { id:"73", name:"lisa"},
   "74" : { id:"74", name:"ida"},
   "75" : { id:"75", name:"ali"}       
}

Upvotes: 0

Views: 40

Answers (2)

Fals
Fals

Reputation: 6839

You should use Jquery $.merge:

var obj1 = {
   "51" : { id:"51", name:"frank" },
   "52" : { id:"52", name:"jonny" }
};

var obj2 = {
   "72" : { id:"72", name:"daniel"},
   "73" : { id:"73", name:"lisa"},
   "74" : { id:"74", name:"ida"},
   "75" : { id:"75", name:"ali"}       
}

var result =  $.extend(obj1, obj2);

Working exemple here

Upvotes: -1

ssube
ssube

Reputation: 48287

Assuming that the ID will always be unique, you can do something like:

var buffer = {};

messageSource.on('message', function (msg) {
    var msgKeys = Object.keys(msg); // Get the list of IDs
    msgKeys.forEach(function (key) { // For each numeric key...
        buffer[key] = msg[key]; // Copy the message
    });
});

If you cannot guarantee unique IDs, you'll need some minor changes:

var buffer = {};

messageSource.on('message', function (msg) {
    var msgKeys = Object.keys(msg);
    msgKeys.forEach(function (key) {
        buffer[key] = (buffer[key] || []).push(msg[key]); // Only change, append to list for that key
    });
});

Upvotes: 4

Related Questions