将JSON中的元素替换为Javascript数组中的元素

时间:2012-11-06 21:49:55

标签: javascript jquery json

我有这个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}]

我有这个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"}]}

我想用第一个JSON中的“描述”替换第一个JSON中的“serial”元素。我在一个JSON中需要它的原因是我使用的是DataTable,我只能传入一个JSON。

我不确定如何在Javascript / JQuery中执行此操作?

2 个答案:

答案 0 :(得分:1)

你可以通过设置小函数来完成这个,而不需要任何jQuery:

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;
}

然后将两段JSON保存到变量中并调用函数:

var json1, json2, mergedJson;

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

mergedJson = replaceSerial (json1, json2);

答案 1 :(得分:0)

假设您的第一个对象名为to,第二个对象名为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