4

我有两个 JSON 提要。第一个包含有关课程的基本信息,第二个包含更多管理性质的信息。这是我的意思的一个示例。

第一的

{"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 匹配的记录合并。

有什么建议么?

谢谢。

4

1 回答 1

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
});
于 2013-02-26T14:49:38.343 回答