I’m trying to merge array of JSON objects to one object using jQuery.extend function.
Assume, i have a sample array:
arr = [{a:4},{b:5}];
in case:
arr.reduce( $.extend )
//result { "1":{b:5}, a:4, b:5 }
but
arr.reduce( function( a, b){ return $.extend(a,b) } );
//is ok: { a:4, b:5 }
why?
The function passed to
reducewill receive four arguments (the last two are the index of the current item and the array thatreducewas called on). You’re only interested in the first two, butjQuery.extendtakes a variable number of arguments, so it slurps them all up. By explicitly writing a function that takes two arguments and passes them toextend, you avoid this and get the behavior you expected.