Reputation:
I've been using this extend:
const extend = require('util')._extend;
but just noticed it modifies the original object:
> let hello = {a: 5};
> extend(hello, {poop: 'whas'})
{ a: 5, poop: 'whas' }
> hello
{ a: 5, poop: 'whas' }
What's a concise way I can extend objects without modifying them?
E.g. I'd want the above repl session to look like:
> let hello = {a: 5};
> extend(hello, {poop: 'whas'})
{ a: 5, poop: 'whas' }
> hello
{ a: 5 }
Upvotes: 1
Views: 202
Reputation: 574
Also, if you're using ES9/ES2018, the simplest solution is just to use the spread operator. It will generally compile down to Object.assign anyway, but it's a much neater syntax.
let hello = {a: 5}
console.log({ ...hello, foo: 'bar' }) // { a: 5, foo: 'bar' }
console.log(hello) // { a: 5 }
Upvotes: 0
Reputation: 228
Since nobody provided an ES5 solution so far, let me give this a shot:
function extend(obj1, obj2) {
if (!window.JSON)
return false;
var _res = JSON.stringify(obj1) + JSON.stringify(obj2);
return JSON.parse(_res.replace('}{', ','));
}
var foo = { 0: 'apple', 1: 'banana', 2: 'peach' };
var bar = { favorite: 'pear', disliked: 'apricot' };
extend(foo, bar); // returns bar
console.log(foo); // { 0: 'apple', 1: 'banana', 2: 'peach' }
console.log(bar); // { 0: 'apple', 1: 'banana', 2: 'peach', favorite: 'pear', disliked: 'apricot' }
Upvotes: 0
Reputation: 2762
use Object.create
const extend = require("util")._extend;
let hello = { a: 5 };
let newObj = _extend(Object.create(hello), { poops: 'whas' });
console.log(newObj.a); // a
console.log(newObj.poops); // whas
console.log(hello.a) // 5
console.log(hello.poops) // undefined
Upvotes: 1
Reputation: 1894
Object.assign is your solution
const object2 = Object.assign({}, object1);
Upvotes: 0