I've tried using merge and extend to combine arrays inside an Autocomplete ajax option - the jQuery Autocomplete UI widget. They both work, but neither as they are supposed to. In the code below using extend(), only the contents of objectB display in the dropdown box. If I reverse the order of the arguments, only objectA displays, i.e., the second argument displays but not the combination with the first. When I开发者_StackOverflow change it to merge( objectA, objectB ), only the contents of objectA display. With merge(), only the first argument displays, but not the combination of both. How do I get the combined contents of both arrays to display? (Eventually, objectB will be completely different, but I'm just trying to get the concept working.)
$.ajax(
{
url: "http://ws.geonames.org/searchJSON",
dataType: "jsonp",
data: geonamesData,
success: function( data )
{ var objectA=null;
var objectB=null;
var objectC=null;
response( $.map( data.geonames, function( item )
{ objectA={
label: item.name + (item.adminName2 ? ", " + item.adminName2 : "") + (item.adminName1 ? ", " + item.adminName1 : "") + ", " + item.countryName,
value: item.name + (item.adminName2 ? ", " + item.adminName2 : "") + (item.adminName1 ? ", " + item.adminName1 : ""),
name: item.name
};
objectB={
label: item.name + (item.adminName2 ? ", " + item.adminName2 : ""),
value: item.name + (item.adminName2 ? ", " + item.adminName2 : ""),
name: item.name
};
objectC=$.extend({},objectA, objectB);
return objectC;
}));
}
});
$.extend
deals with properties - it merges properties leftwards. That is, any properties appearing in "righter" argument will override all same-named properties appearing in any "lefter" argument. (The result is a single object, which is the same object as the first parameter: the first input object is mutated).
$.merge
can be thought of a "concat" -- but see note -- as it concatenates two arrays (or array-like things) together. (The result is a single array, which is the same object as the first parameter: the first input array is mutated.)
If you want a collection of items, return a collection of the items (normally an array).
E.g. return [objectA, objectB]
.
Happy coding.
精彩评论