How to merge few 3D JSON objects in JS [or jQuery]
I have to merge 2 (up to 6) JSON objects.
I got this code: http://jsfiddle.net/5Uz27/
But with this code, I can only merge the first level of the objects, so the deeper levels are usually overwritten. Check the output.开发者_开发问答
How can I fix that?
jQuery.extend(true, original_object, extend_with);
source: http://api.jquery.com/jQuery.extend/
With jQuery, you can use $.extend()
to do a "deep"/recursive merge of objects, by passing in true
as the first argument.
Here's how this might work in your example:
// 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 );
This might be a little obtuse (you could make it even more so, but tighter, by setting pref_array
to [true].concat($.map(json_holder, JSON.parse))
), but it avoids the ungainly for
loop (that might be personal preference, I suppose).
Working jsFiddle here: http://jsfiddle.net/e6bnU/
精彩评论