简体   繁体   English

无需修改即可扩展对象(功能扩展)

[英]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:例如,我希望上面的 repl 会话看起来像:

> let hello = {a: 5};
> extend(hello, {poop: 'whas'})
{ a: 5, poop: 'whas' }
> hello
{ a: 5 }

use Object.create使用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.此外,如果您使用的是 ES9/ES2018,最简单的解决方案就是使用扩展运算符。 It will generally compile down to Object.assign anyway, but it's a much neater syntax.无论如何,它通常会编译为 Object.assign,但它的语法要简洁得多。

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:由于到目前为止没有人提供 ES5 解决方案,让我试一试:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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