Path: csiph.com!.POSTED.208-71-239-109.cust.centrio.cz!not-for-mail From: Cezary Tomczyk Newsgroups: comp.lang.javascript Subject: Re: Cloning an object Date: Thu, 5 Jul 2018 10:00:53 +0200 Organization: csiph.com Internet News Service Message-ID: References: <1620852.VI2in3QvqR@PointedEars.de> <9909bfec-c6e7-2a4a-2a54-ec9f271691c8@PointedEars.de> <4395113.31r3eYUQgx@PointedEars.de> Mime-Version: 1.0 Content-Type: text/plain; charset=utf-8; format=flowed Content-Transfer-Encoding: 7bit Injection-Date: Thu, 5 Jul 2018 08:00:54 -0000 (UTC) Injection-Info: csiph.com; posting-host="208-71-239-109.cust.centrio.cz:109.239.71.208"; logging-data="96787"; mail-complaints-to="admin@kev009.com" User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.13; rv:52.0) Gecko/20100101 Thunderbird/52.8.0 In-Reply-To: <4395113.31r3eYUQgx@PointedEars.de> Content-Language: en-US Xref: csiph.com comp.lang.javascript:35349 On 04/07/2018 23:25, Thomas 'PointedEars' Lahn wrote: [...] > Deep copies are easy with recursion. In this case, tested in > navigator.userAgent === "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 > (KHTML, like Gecko) Chrome/57.0.2987.98 Safari/537.36": > > function clone (obj, deepCopy) > { > const CLONE = Object.create(Object.getPrototypeOf(obj)); > > Object.getOwnPropertyNames(obj).forEach((name) => { > const DESC = Object.getOwnPropertyDescriptor(obj, name); > > if (deepCopy) > { > /* FIXME: Standardize Object.isObject() */ > if (("value" in DESC) > && (typeof DESC.value == "object") > && (DESC.value != null)) > { > DESC.value = clone(DESC.value); > } > } > > Object.defineProperty(CLONE, name, DESC || {}); > }); > > return CLONE; > } > > const ORIG = {foo: {bar: "baz"}}; > const CLONE = clone(ORIG, true); > > /* "baz" */ > console.log(CLONE.foo.bar); > > CLONE.foo.bar = 42; > > /* 42 */ > console.log(CLONE.foo.bar); > > /* "baz" */ > console.log(ORIG.foo.bar); > > See also jsx.object.clone() in JSX:object.js (not yet adapted to ES 6, but > with more options): > > It passes for simple objects, but if the property has a value as an array or Date object then it doesn't work. But I think above solution can be enhanced to support it. -- Cezary Tomczyk http://www.ctomczyk.pl/ https://www.aslint.org/