合并两个对象数组

时间:2014-06-02 12:03:20

标签: javascript arrays object

我有一个问题,我现在很长一段时间都在苦苦挣扎。我有两个数组:

var arr1 = [{"x":1,"y":1,"value":null},{"x":2,"y":1,"value":null},{"x":3,"y":1,"value":null},{"x":4,"y":1,"value":null},{"x":5,"y":1,"value":null},{"x":1,"y":2,"value":null},{"x":2,"y":2,"value":null},{"x":3,"y":2,"value":null},{"x":4,"y":2,"value":null},{"x":5,"y":2,"value":null},{"x":1,"y":3,"value":null},{"x":2,"y":3,"value":null},{"x":3,"y":3,"value":null},{"x":4,"y":3,"value":null},{"x":5,"y":3,"value":null},{"x":1,"y":4,"value":null},{"x":2,"y":4,"value":null},{"x":3,"y":4,"value":null},{"x":4,"y":4,"value":null},{"x":5,"y":4,"value":null},{"x":1,"y":5,"value":null},{"x":2,"y":5,"value":null},{"x":3,"y":5,"value":null},{"x":4,"y":5,"value":null},{"x":5,"y":5,"value":null}];

var arr2 = [{"x":1,"y":1,"value":13},{"x":1,"y":3,"value":3},{"x":2,"y":2,"value":146},{"x":2,"y":3,"value":44},{"x":2,"y":4,"value":42},{"x":2,"y":5,"value":5},{"x":3,"y":2,"value":14},{"x":3,"y":3,"value":57},{"x":3,"y":4,"value":23},{"x":3,"y":5,"value":15},{"x":4,"y":2,"value":1},{"x":4,"y":3,"value":4},{"x":4,"y":4,"value":8},{"x":4,"y":5,"value":1},{"x":5,"y":4,"value":1},{"x":5,"y":5,"value":8}];

arr1总是包含25个对象,arr2包含可变数量的对象,但它们的格式始终相同。

如何将两个数组合并为一个数组,例如:

结果,来自arr1的

{"x":1,"y":1,"value":null}将是{"x":1,"y":1,"value":13},但arr1中的{"x":2,"y":1,"value":null}将保持不变,因为arr2没有此对象。

合并之后,最理想的是拥有一个包含25个对象的数组,其中字段"value"从arr2中的对象中填充。

修改 好吧,因为我得到了很多downvotes,你可以在JSFiddle

找到我的代码

非常感谢任何帮助!

1 个答案:

答案 0 :(得分:1)

如果这是一个选项,您可以使用jQuery extend来实现此目的。

var extendedArray = $.extend({}, arr1, arr2);

上面的代码将为您创建一个新对象,其中包含您请求的内容。如果您不想要新对象,请使用

$.extend(arr1, arr2);

请参阅上面提到的文档以获取更多信息(例如深度扩展等)。