This question has already been answered:

Implement the extend(obj1, obj2) function that copies the properties from the obj2 object to the obj1 object. The function must return obj1. Values ​​of identical keys must grind the original. Example:

 extend({foo: 'bar', baz: 1}, {foo: true, zoop: 0}); // {foo: true, baz: 1, zoop: 0} 

I thought to do it through some method, but I did not find it ...
I read and read about the methods, but nowhere did I see how to copy the properties of one into another.

Reported as a duplicate at Grundy. javascript Jan 31 '17 at 6:47 .

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

  • @Yres, If you are given a comprehensive answer, mark it as correct (click on the check mark next to the selected answer). - Vitalina
  • @ Vitalina ♦ @Expert ♦♦ full take of the question . To combine. - Sergiks

3 answers 3

For deep copying, it is not enough to transfer the entire nested object to the property - this will be a link to it, and not a new object; you need to go through each element.

 function extend(obj1, obj2){ function copyObject(obj){ var result = {}; for (key in obj) { if(typeof(obj[key]) != 'object'){ result[key] = obj[key]; } else { result[key] = copyObject(obj[key]) } } return result; } for (key in obj2){ if(typeof(obj2[key]) != 'object'){ obj1[key] = obj2[key]; } else { obj1[key] = copyObject(obj2[key]); } } return obj1; } 

    See, for example, how this is done (the extend() method) in the Underscore library:

      _.extend = function(obj) { if (!_.isObject(obj)) return obj; var source, prop; for (var i = 1, length = arguments.length; i < length; i++) { source = arguments[i]; for (prop in source) { if (hasOwnProperty.call(source, prop)) { obj[prop] = source[prop]; } } } return obj; }; 

      Here is the code to copy an object with all the properties. Attention: if the property has an object, then its properties will not be copied, for "deep" copying you need to use recursion:

       function extend(obj1, obj2){ for (key in obj2){ obj1[key]=obj2[key]; } return obj1; } 
      • Yes, I do not need an object to copy. You need the property of one object to copy to another object. - Capricorn
      • The code given by me completely corresponds to the condition of the problem, check. - Chemaxa