0

私はこの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 の「serial」要素を、この JSON の「説明」に置き換えたいと思います。1 つの JSON でそれが必要な理由は、DataTable を使用していて、渡すことができる JSON は 1 つだけだからです。

Javascript / JQueryでこれを行う方法がわかりませんか?

4

2 に答える 2

1

小さな関数を設定することで、jQuery を使用せずにこれを実現できます。

デモフィドルを参照

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

次に、2 つの JSON を変数に保存し、関数を呼び出します。

var json1, json2, mergedJson;

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

mergedJson = replaceSerial (json1, json2);
于 2012-11-06T22:32:39.400 に答える
0

to最初のオブジェクトが呼び出され、2 番目のオブジェクトが呼び出されると仮定します。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;
});

デモ

于 2012-11-06T22:16:40.703 に答える