Design & Download
Your JS Library
in Seconds!!!

Snippet: copyProps()

Written by Christopher West (cwest) on August 15, 2017.
Copy specific properties from one object to another.
function copyProps(target, source, props) {
  var isArray = typeOf(props, 'Array');
  walk(props, function(value, name) {
    if (has(source, value)) {
      target[isArray ? value : name] = source[value];
    }
  });
  return target;
}

copyProps(...) API Documentation

Copy specific properties from one object to another.

Parameters

  1. target {Object}:
    The object into which the properties will be copied.
  2. source {Object}:
    The object from which the properties will be copied.
  3. source {Array|Object}:
    If an array is supplied, it will be treated as an array of property names to copy. If an object is supplied the values will be used as the property names to copy from source and the keys will be the property names to copy to target. Any properties specified that do not exist in source will be ignored.

Returns

The same target object passed in.

Example

var source = { one: 0, two: 2, three: 3 };

var target1 = YourJS.copyProps({ one: 1, three: 2 }, source, ['two', 'three']);
console.log(target1.one);  // -> 1
console.log(target1.two);  // -> 2
console.log(target1.three);  // -> 3

var target2 = YourJS.copyProps({ one: 1, three: 2 }, source, { dos: 'two', tres: 'three' });
console.log(target2.one);  // -> 1
console.log(target2.two);  // -> undefined
console.log(target2.dos);  // -> 2
console.log(target2.three);  // -> 2
console.log(target2.tres);  // -> 3