What’s the best/standard way of merging two associative arrays in JavaScript? Does everyone just do it by rolling their own for
loop?
function extend(objects) {
var args
, first = Array.prototype.slice.call(arguments, 0, 1)[0]
, second;
if (arguments.length > 1) {
second = Array.prototype.splice.call(arguments, 1, 1)[0];
for (var key in second) {
first[key] = second[key];
}
args = Array.prototype.slice.call(arguments, 0);
return extend.apply(this, args);
}
return first;
}
...
var briansDirections = {
step1: 'Remove pastry from wrapper.',
step2: 'Place pastry toaster.',
step3: 'Remove pastry from toaster and enjoy.',
};
extend(briansDirections, { step1: 'Toast Poptarts' }, { step2: 'Go ahead, toast \'em' }, { step3: 'Hey, are you sill reading this???' });
...
This simply extends a splat of objects, recursively. Also, note that this recursive function is TCO (Tail-Call Optimized) as its return is the last call to itself.
Additionally, you may want targeted properties. In this case, you may want to condense objects based upon id
, quantity
, or another property. This approach could have a small book written about it and requires object-juxtaposition and can get very complex. I've written a small library for this which is available upon request.
Hope this helps!