user3310334
user3310334

Reputation:

extend object without modifying (functional extend)

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

Answers (4)

adomnom
adomnom

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

baeyun
baeyun

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

0.sh
0.sh

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

Fabien Greard
Fabien Greard

Reputation: 1894

Object.assign is your solution

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

Upvotes: 0

Related Questions