What's the best/standard way of merging two associative arrays in javascript? Does everyone just do it by rolling their own for loop?
+1
A:
- In Javascript there is no notion of associative array, there are objects
- The only way to merge two objects is to loop for their properties and copy pointers to their values that are not primitive types and values for primitive types to another instance
Sergey Ilinsky
2009-05-30 14:13:12
Objects in Javascript are implemented as associative arrays, so there certainly is the notion of same
George Jempty
2009-05-30 14:16:09
+6
A:
This is how Prototype does it:
Object.extend = function(destination, source) {
for (var property in source)
destination[property] = source[property];
return destination;
};
called as, for example:
var arr1 = { robert: "bobby", john: "jack" };
var arr2 = { elizabeth: "liz", jennifer: "jen" };
var shortnames = Object.extend(arr1,arr2);
Jonathan Fingland
2009-05-30 14:16:45
You'll need the test source.hasOwnProperty(property) to make sure you only copy the immediate properties over. As it is, this could will copy all properties including those derived from Object.prototype
bucabay
2009-09-20 18:54:14
+1
A:
do you want to overwrite a property if the names are the same but the values are not?
And do you want to permanently change one of the original objects,
or do you want a new merged object returned?
function mergedObject(obj1, obj2, force){
for(var p in obj1) this[p]= obj1[p];
for(var p in obj2){
if(obj2.hasOwnProperty(p)){
if(force || this[p]=== undefined) this[p]= obj2[p];
else{
n= 2;
while(this[p+n]!== undefined)++n;
this[p+n]= obj2[p];
}
}
}
}
kennebec
2009-05-30 16:07:42
+2
A:
In dojo, the 2-objects/arrays "merge" would be dojo.mixin(destination, source)
-- you can also mix multiple sources into one destination, etc -- see the mixin function's reference for details.
Alex Martelli
2009-05-30 16:29:51
+1
A:
with jquery you can call $.extend
obj1 = {a: 1, b: 2};
obj2 = {a: 4, c: 110};
obj3 = $.extend(obj1, obj2);
obj1 == obj3 == {a: 4, b: 2, c: 110}
(assoc. arrays are objects in js)
look here: http://api.jquery.com/jQuery.extend/
kulpae
2010-07-05 21:23:08