4

Is there a language-level way to deep clone a JavaScript object that is supported by main browsers (desktop and mobile)? I've seen that eval(uneval(o)); is non-standard.

JSON.parse(JSON.stringify(o)); looks ugly. You don't fundemantally need to 'stringify' at the first place. Just copy the bytes from the object to somewhere else in the RAM. Anything done above this looks like an inefficiency to me.

I am surprised to see that there is not this kind of functionality in various languages...

yılmaz
  • 365
  • 1
  • 14
  • 1
    There is [`structuredClone()`](https://developer.mozilla.org/en-US/docs/Web/API/structuredClone), but it's new and not supported by many browsers yet. stringifying and parsing is the simplest option. You could always write a recursive function to do the cloning for your though – Nick Parsons Dec 16 '21 at 06:05
  • 1
    [`structuredClone`](https://developer.mozilla.org/en-US/docs/Web/API/structuredClone) is probably the closest thing. It’s barely supported right now, but there are other ways to make structured clones. “Just copy the bytes from the object to somewhere else in the ram” doesn’t work for a lot of types behind the scenes, like pointers. – Ry- Dec 16 '21 at 06:05
  • 8
    **Deep cloning is hard.** Trying to deep clone *every kind of objects* can bring up many ambiguities, problems, etc. What to do with functions having closures? What to do with class instances? What about class instances that are meant to be unique? Class instances with private fields? Symbols? Prototypes? Proxies? If the cloning can be constrained to plain objects, arrays, Maps and Sets, it would resolve many of these problems. – FZs Dec 16 '21 at 06:23
  • https://stackoverflow.com/a/10916838/1048572 – Bergi Dec 16 '21 at 07:41

1 Answers1

-4

All objects are actually clones of their respective prototypes...

There is a reason we have Object constructors. Meaning :: You can write an object constructor, and clone it as many times you as need to.

Of course this may not be the "language-level" way that you expect, but truly - that's the real procedural way JavaScript Objects are supposed to be created.

We don't do that because JavaScript is a relaxed language, meant to be programmer friendly and not a pain in the rear like they're trying to make it, so we forget our manners.

However, writing constructors for deep Objects is not an easy task at all. -But I'm pretty sure it is not all that impossible.

Bekim Bacaj
  • 5,707
  • 2
  • 24
  • 26