我必须合并2个(最多6个)JSON对象。如何合并JS [或jQuery]中的几个3D JSON对象
我得到这个代码:http://jsfiddle.net/5Uz27/
但有了这个代码,我只能合并对象的第一级,所以更深层次通常被覆盖。检查输出。
我该如何解决这个问题?
我必须合并2个(最多6个)JSON对象。如何合并JS [或jQuery]中的几个3D JSON对象
我得到这个代码:http://jsfiddle.net/5Uz27/
但有了这个代码,我只能合并对象的第一级,所以更深层次通常被覆盖。检查输出。
我该如何解决这个问题?
jQuery.extend(true,original_object,extend_with);
使用jQuery,您可以使用$.extend()
做“深” /递归对象合并,由true
传递作为第一个参数。
以下是这可能会在你的榜样工作:
// turn the strings into objects
var pref_array = $.map(json_holder, JSON.parse);
// add the deep=true argument
pref_array.unshift(true);
// now do a deep extend, passing the array as arguments
var prefs = $.extend.apply(null, pref_array);
这可能有点钝(你可以使它更是这样,但更严格,通过设置pref_array
到[true].concat($.map(json_holder, JSON.parse))
),但它避免了难看for
循环(这可能是个人喜好,我想)。
在这里工作jsFddle:http://jsfiddle.net/e6bnU/