Envin
Envin

Reputation: 1523

Replace Element in JSON with a element in a Javascript array

I have this JSON

[{"id":7,"serial":"7bc530","randomDouble":0.0,"randomDouble2":0.0,"randomDouble3":0.0,"date":1352228474000,"removed":null},
{"id":8,"serial":"4a18d27","randomDouble":0.0,"randomDouble2":0.0,"randomDouble3":0.0,"date":1352228474000,"removed":null},
{"id":9,"serial":"f30ef","randomDouble":0.0,"randomDouble2":0.0,"randomDouble3":0.0,"date":1352228474000,"removed":null},
{"id":10,"serial":"9e6d","randomDouble":0.0,"randomDouble2":0.0,"randomDouble3":0.0,"date":1352228474000,"removed":null},
{"id":11,"serial":"4d8665a3","randomDouble":0.0,"randomDouble2":0.0,"randomDouble3":0.0,"date":1352228474000,"removed":null},
{"id":12,"serial":"4fe1457","randomDouble":0.0,"randomDouble2":0.0,"randomDouble3":0.0,"date":1352228474000,"removed":null}]

and I have this JSON

{"computers":[{"id":"7bc530","name":"Dell","description":"Dell"},
{"id":"f30ef","name":"HP","description":"HP"},
{"id":"9e6d","name":"Compaq","description":"Compaq"},
{"id":"4d8665a3","name":"Toshiba","description":"Toshiba"},
{"id":"4fe1457","name":"Asus","description":"Asus"},
{"id":"4a18d27","name":"Acer","description":"Acer"}]}

I want to replace the "serial" element in the first JSON with the "Description" in this one. The reason why I need it in one JSON is that I am using a DataTable and I can only pass one JSON in.

I'm not sure how I can do this in Javascript / JQuery?

Upvotes: 0

Views: 5617

Answers (2)

Steven Schobert
Steven Schobert

Reputation: 4269

You can accomplish this without any jQuery by setting up small function:

(see the demo fiddle)

function replaceSerial (data1, data2) {
    var descs = {}, computers = data2['computers'], final = data1;

    for (var i = 0; i < computers.length; i++ ) {
        descs[computers[i]['id']] = computers[i]['description'];
    }

    for (var i = 0; i < data1.length; i++) {
        final[i]['serial'] = descs[data1[i]['serial']];
    }

    return final;
}

Then just save your two pieces of JSON into variables and invoke the function:

var json1, json2, mergedJson;

json1 = // DATA IN FIRST JSON;
json2 = // DATA IN SECOND JSON;

mergedJson = replaceSerial (json1, json2);

Upvotes: 1

clentfort
clentfort

Reputation: 2504

Assuming your first object is called to and the second object is called from

// Iterate over each entry in to
to.forEach(function(value) {
    // In each iteration find elements in from where the id is the same
    // as the serial of the current value of to
    var description = from.computers.filter(function(element){
        if (element.id == value.serial) return true;
    });
    // Copy description of first found object in the description property of
    // the current object
    value.description = description[0].description;
    // Unset serial?
    delete value.serial;
});

DEMO

Upvotes: 0

Related Questions