repl.it
JavaScript

Underscore Extend object method implementation in JS

fork
loading
main.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
extend = function(destination, source) {
  if (destination === null || typeof destination !== 'object') {
     return destination;
  }
  
  if (source === null || typeof source !== 'object') {
    return source;
  }

  for (var key in source) {
    if (source.hasOwnProperty(key)) {
      destination[key] = extend(source[key]);
    }
  }

  return destination;
}

let sourceObj = {name: 'John Smith', age: 24};
let destinationObj = {ID: 123490};

extend(destinationObj, sourceObj);
// => { ID: 123490, name: 'John Smith', age: 24 }
Native Browser JavaScript