简体   繁体   中英

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?

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

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

Object.assign是您的解决方案

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

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 }

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM