Sunday, May 12, 2024
46
rated 0 times [  50] [ 4]  / answers: 1 / hits: 103780  / 12 Years ago, thu, december 13, 2012, 12:00:00

I'm sick & tired of always having to write code like this:


function shallowExtend(obj1,obj2){
var key;
for ( key in obj2 ) {
if ( obj2.hasOwnProperty(key) === false ) continue;
obj1[key] = obj2[key]
}
}

Or if I don't want to write the code myself, implement a library that does it already. Surely ES6+ is coming to the rescue on this will provide us with something like a Object.prototype.extend(obj2...) or Object.extend(obj1,obj2...)


So does ES6+ provide such functionality? If not already there, then is such functionality planned? If not planned, then why not?


More From » ecmascript-6

 Answers
4

You will be able to do a shallow merge/extend/assign in ES6 by using Object.assign:



https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign



Syntax:




Object.assign(target, sources);




where ...sources represents the source object(s).



Example:



var obj1 = {name: 'Daisy', age: 30};
var obj2 = {name: 'Casey'};

Object.assign(obj1, obj2);

console.log(obj1.name === 'Casey' && obj1.age === 30);
// true

[#81453] Wednesday, December 12, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
bradenc

Total Points: 75
Total Questions: 96
Total Answers: 129

Location: Burundi
Member since Thu, Feb 10, 2022
2 Years ago
bradenc questions
Thu, Sep 2, 21, 00:00, 3 Years ago
Wed, Sep 1, 21, 00:00, 3 Years ago
Wed, May 6, 20, 00:00, 4 Years ago
Tue, Oct 8, 19, 00:00, 5 Years ago
;