Wednesday, July 12, 2017

Copy object properties

function copyAll(source, target) {
 for (var prop in source) {
  target[prop] = source[prop];
 } 
}
var emp = {};
var joe = {
 name: 'Joe',
 age: 36
}
copyAll(joe, emp);
console.log(emp);
var sam = {
 name: 'Sam',
 age: 28,
 desig: 'Dev'
}
var hasOwnProp = Object.prototype.hasOwnProperty;
function hasProp(obj, prop) {
 return hasOwnProp.call(obj, prop);
}
function copyNew(source, target) {
 for (var prop in source) {
  if (!hasProp(target, prop)) {
   target[prop] = source[prop];
  }
 } 
}
copyNew(sam, joe);
console.log(joe);
var painter = {
 school: 'ArtSchool',
 medium: 'watercolour'
}
var jay = Object.create(painter);
jay.name = 'Jay';
jay.genre = 'Realism';
jay.trainer = {
 onSkype: true,
 inPerson: true,
 duration: 0.5
}
function copyDeep(source, target) {
 for (var prop in source) {
  if (!hasProp(target, prop)) {
   if (source[prop] === 'object') {
    target[prop] = {};
    copyDeep(source[prop], target[prop]);
   } else {
    target[prop] = source[prop];
   }
  }
 } 
}
var alice = Object.create(painter);
alice.name = 'Alice';
copyDeep(jay, alice);
console.log(alice);
Output:
{ name: 'Joe', age: 36 }
{ name: 'Joe', age: 36, desig: 'Dev' }
{ name: 'Alice',
  genre: 'Realism',
  trainer: { onSkype: true, inPerson: true, duration: 0.5 },
  school: 'ArtSchool',
  medium: 'watercolour' }


No comments:

Post a Comment