1

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 }
2
  • All extend functions extend their first argument. You are looking for a copy function it seems. Commented Mar 4, 2018 at 12:02
  • 3
    extend({}, hello, {poop: 'whas'}) extends a new object (the object literal) not hello. Commented Mar 4, 2018 at 12:02

4 Answers 4

1

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
Sign up to request clarification or add additional context in comments.

Comments

0

Object.assign is your solution

const object2 = Object.assign({}, object1);

3 Comments

util.extend does the same as Object.assign.
I thought this doesn't do deep copies
Oh indeed it does the same, i didn"t know, thanks Bergi :)
0

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' }

Comments

0

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 }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.