javascript - Merge 2 objects values when key is same -


i have 2 objects:

{'1': {'a': 1, 'b': 2, 'c': 3}}, {'1': {'d': 4, 'e': 5, 'f': 6}, '2': {'g': 7}}. 

is there function in native javascript (underscore being used in project) can put in both objects , out?

{'1': {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6}, '2': {'g': 7}} 

[updated] use following merging without affecting original objects:

var isobject = function(o) { return object.prototype.tostring.call(o) == '[object object]'; }; var isarray = function(o) { return object.prototype.tostring.call(o) == '[object array]'; };  function extend(a, b) {   (var prop in b) {     if (isobject(b[prop])) {       extend(a[prop]||(a[prop] = {}), b[prop]);     }     else if (isarray(b[prop])) {       a[prop] = (a[prop]||[]).concat(b[prop]);     }     else {       a[prop] = b[prop];     }   }   return a; }  function merge(dest, source) {   var obj = extend({}, dest),       sources = arguments.length > 2 ? [].slice.call(arguments,1) : [source];    sources.foreach(function(source) {     extend(obj, source);   });    return obj; } 

see working jsbin.

this updated version should allow merge more 1 object , returns copy of merged objects, leaving originals in place.


Comments

Popular posts from this blog

database - VFP Grid + SQL server 2008 - grid not showing correctly -

jquery - Set jPicker field to empty value -

.htaccess - htaccess convert request to clean url and add slash at the end of the url -