合并两个Javascript对象

时间:2014-06-05 15:58:18

标签: javascript jquery

我有两个对象

var data = {property: [
  {id: "1", name: "Snatch", type: "crime"},
  {id: "2", name: "Witches of Eastwick", type: "comedy"},
  {id: "3", name: "X-Men", type: "action"},
  {id: "4", name: "Ordinary People", type: "drama"},
  {id: "5", name: "Billy Elliot", type: "drama"},
  {id: "6", name: "Toy Story", type: "children"}
]};

var data = {property: [
  {id: "7", name: "Snatch", type: "crime"},
  {id: "8", name: "Witches of Eastwick", type: "comedy"}
]};

我可以使用jquery或javascript将两者结合起来,如下所示

var data = {property: [
  {id: "1", name: "Snatch", type: "crime"},
  {id: "2", name: "Witches of Eastwick", type: "comedy"},
  {id: "3", name: "X-Men", type: "action"},
  {id: "4", name: "Ordinary People", type: "drama"},
  {id: "5", name: "Billy Elliot", type: "drama"},
  {id: "6", name: "Toy Story", type: "children"},
  {id: "7", name: "Snatch", type: "crime"},
  {id: "8", name: "Witches of Eastwick", type: "comedy"}
]};

我尝试过使用推送功能,但没有运气

2 个答案:

答案 0 :(得分:2)

怎么样:

var data = {property: []}

var data2 = {property: []}

data.property =data.property.concat(data2.property);

使用数组的concat功能,您可以加入它们。

答案 1 :(得分:0)

concat是一种解决方案,但underscore.js' union也会处理任何重复项。

var data3 = _.union(data.property, data2.property)