4 ms·
I only clone data using JSON.parse(JSON.stringify(someThing)), and thus avoid all the mess that comes with trying to clone anything else than primitives types.
by RedShift1 4y ago
I only clone data using JSON.parse(JSON.stringify(someThing)), and thus avoid all the mess that comes with trying to clone anything else than primitives types.
- jakear 4y agoI sure hope `someThing` is never `undefined`, for your sake.
- RedShift1 4y agoAny cloning happens on data retrieved from an API, which is always JSON, and cannot contain undefined by definition.
- grensley 4y agoJust chuck a check in front of it
- dspillett 4y agoThat seems to be a logical thing to ensure has been validated before this code is run, so no need to complicate the simple example in a HN post?
- jakear 4y ago> avoid all the mess that comes with trying to clone anything else than primitives types is an odd way to suffix code that will throw a SyntaxError when handed a primitive type.
- Gare 4y agoOr NaN or Infinity.
- ravenstine 4y agoThere's this really nifty concept called "guarding" that helps with recovering from that sort of thing.
- hutzlibu 4y agoWhich is the first method they mention and just flat out tell to avoid it. "cloneJSON is very slow and can’t do much. Please avoid it." I mean, I also use it since forever. But I might look into the winner cloneLib. If it is really faster, it might be worth it, but I likely still won't trust it for anything complex.
- RedShift1 4y agoEmphasis on _data_. I don't have a need to clone complex objects (what the article is trying to do). The data I need to clone are usually small so when it comes to performance it's negligible, not worth adding another dependency to the project.
- nishs 4y agoThis fails, among other scenarios, if `someThing` includes a Date object. >>> const z = { d: new Date() } undefined >>> typeof z.d "object" >>> const a = JSON.parse(JSON.stringify(z)) undefined >>> typeof a.d "string" >>> After the roundtrip, the property `d` is now a string, not a Date object.
- RedShift1 4y agoAll the data comes from a JSON API and thus doesn't contain Date objects to begin with.
- deleted 4y ago[deleted]
- nishs 4y agoMakes sense for the most part with these constraints then. I missed the "primitive types" portion in the original comment. The following isn't applicable for pure JSON responses, but is applicable for primitive types: An additional condition for bigint is necessary, which is a primitive type. Otherwise JSON.stringify throws: >>> const x = { i: BigInt("0x1fffffffffffff") } undefined >>> typeof x.i "bigint" >>> const b = JSON.parse(JSON.stringify(x)) Exception: TypeError: JSON.stringify cannot serialize BigInt. >>> ... and for the symbol primitive, which JSON.stringifys to undefined, and thus can't be JSON.parsed.
- sieabahlpark 4y ago[dead]
- ravenstine 4y agoConsider the Date object harmful, use ISO strings instead, and problem solved.
- eurasiantiger 4y agoSo how do you manipulate ISO dates as strings?