【问题标题】:Merge two JSON objects that have a common element合并两个具有共同元素的 JSON 对象
【发布时间】:2013-02-26 14:26:42
【问题描述】:

我有两个 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 匹配的所有记录。

有什么建议吗?

谢谢。

【问题讨论】:

  • 你试过什么? - First post - Second post - Third post 如果这些都没有帮助,为什么?是什么让您的问题与其他人不同?
  • 第一篇文章只是将两个相同的提要合并在一起......
  • 第二篇文章我不知道它是怎么回事,因为数据样本无法再访问了
  • 第三篇又是关于将两个对象合并为一个...
  • 我想要做的是将 JSON 元素合并为一个元素,如果它们的 id 编号匹配。我不想只是将两个 JSON 提要添加到一个长提要中……而 JSON 元素是指一条记录。

标签: javascript jquery ajax json


【解决方案1】:
$.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
});

【讨论】:

  • @JanDvorak:是的,谢谢。我永远不确定$.when 是如何结合这些论点的
  • 不错的代码块,但没有解释并没有真正的帮助。您正在提高 OP 的复制和粘贴技能,而不是他的技术技能……
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-09-04
  • 1970-01-01
  • 2020-10-27
  • 2018-09-14
  • 1970-01-01
  • 2018-01-14
  • 2017-10-17
相关资源
最近更新 更多