2013-02-26 38 views
4

我有兩個JSON提要。一個包含關於課程的基本信息,第二個包含更具管理性質的信息。這是我的意思的一個例子。合併兩個具有公共元素的JSON對象

FIRST

{"courses": 
    {"course":{"id":"4","title":"Using a computer","body":"36"}} 
    ,{"course":{"id":"5","title":"Job hunting online","body":"29"}} 
} 

第二

{"courses": 
    {"4": {"id":4,"name":"Online Basics","title":"Using a computer","shortname":"onlinebasics","height":640,"width":980,"html5":1,"url":"\/sites\/default\/files\/courses\/onlinebasics\/wrapper.html","started_on":"","bundle_only":true,"progress":false,"completed_on":"2012\/10\/31 00:12:39","on_planner":true} 
    ,"5": {"id":5,"name":"Online Basics","title":"OB2 Job hunting online","shortname":"onlinebasics","height":640,"width":980,"html5":1,"url":"\/sites\/default\/files\/courses\/onlinebasics\/wrapper.html","started_on":"","bundle_only":true,"progress":false,"completed_on":"2012\/11\/24 02:14:51","on_planner":false} 
    } 
} 

所需的輸出

{"courses": 
    {"course":{"id":"4","title":"Using a computer","body":"36","name":"Online Basics","title":"Using a computer","shortname":"onlinebasics","height":640,"width":980,"html5":1,"url":"\/sites\/default\/files\/courses\/onlinebasics\/wrapper.html","started_on":"","bundle_only":true,"progress":false,"completed_on":"2012\/10\/31 00:12:39","on_planner":true}} 
} 

我希望加入的「期望輸出」選項將使其更易於理解。儘管我只將1個示例放入了所需的輸出區域,但我希望所有記錄都是id匹配的合併記錄。

有什麼建議嗎?

謝謝。

+0

我試過使用JQuery.extend但對我來說根本沒用......我試圖實現的是將課程詳細信息feed中的記錄與管理源中的記錄合併到哪裏id號匹配,然後將該輸出傳遞給第三個新元素。 – 2013-02-26 14:46:50

+0

你有什麼試過的? - [第一篇文章](http://stackoverflow.com/questions/3857152/jquery-merge-multiple-json-results) - [Second post](http://stackoverflow.com/questions/8478260/merge-two -json-objects-with-jquery) - [Third post](http://stackoverflow.com/questions/10384845/merge-two-json-objects-in-to-one-object)如果這些都沒有幫助,爲什麼?是什麼讓你的問題與別人不同? – Michal 2013-02-26 14:31:57

+0

第一篇文章是關於合併兩個相同的飼料在一起... – 2013-02-26 14:36:49

回答

7
$.when($.get("feed1.json"), $.get("feed2.json")).done(function(basics, admin) { 
    var basiccourses = basics[0].courses, 
     admincourses = admins[0].courses; 
    // merge all basic course objects into the admin courses object 
    for (var i=0; i<basiccourses.length; i++) { 
     var basic = basiccourses[i]; 
     if (basic.id in admincourses) 
      // by extending the course object 
      $.extend(admincourses[basic.id], basic); 
     else 
      // or just copying it over 
      admincourses[basic.id] = basic; 
    } 

    // now admincourses has all information combined 
}); 
+0

@JanDvorak:是的,謝謝。我不知道['$ .when'](http://api.jquery.com/jQuery.when/)如何結合參數 – Bergi 2013-02-26 14:54:13

+0

現在看起來不錯:-) – 2013-02-26 14:56:31

+3

不錯的代碼塊,但沒有解釋沒有什麼幫助。您正在改進OP的複製和粘貼技巧,而不是他的技術技能...... – Christoph 2013-02-26 14:59:16