2012-11-06 173 views
0

我有这样的JSON在JSON与元素在Javascript数组

[{"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中是因为我使用的是DataTable,而且我只能传入一个JSON。

我不知道如何在Javascript/JQuery中做到这一点?

+1

我在快乐1猜测串行ID是2,所以遍历第一个引用的第二个来填充第一一。 –

+0

都是同一顺序的数组? – charlietfl

+0

提示:迭代第一个,并使用序列键的值来查找第二个条目中的条目...我将实现留给你,以便不干涉@undefined的问题;-) – awenkhh

回答

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); 
+0

如果我的“data1”json没有名字,该怎么办?第二个名称是“computers”,但第一个没有。 – envinyater

+0

我不确定我了解你的问题。你能更具体一些,还是举个例子?您可以通过将它分配给一个变量来为您的json分配一个“名称”。 JSON是本质上有效的javascript。你发布的第一条JSON是一个数组'''',你发布的第二条是一个对象'{}'。 –

+0

我能够得到这个工作,谢谢:) – envinyater

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

+0

应该注意''forEach'不适用于所有浏览器,如IE <9 – charlietfl

+0

而且在一些浏览器中没有JavaScript这样的as lynx;) – clentfort