https://github.com/cdaringe/primitivify
deep copy data keeping only primitives in nested data structures
https://github.com/cdaringe/primitivify
clone json primitives serialization stringify
Last synced: 2 months ago
JSON representation
deep copy data keeping only primitives in nested data structures
- Host: GitHub
- URL: https://github.com/cdaringe/primitivify
- Owner: cdaringe
- Created: 2019-10-25T23:54:58.000Z (over 5 years ago)
- Default Branch: main
- Last Pushed: 2025-01-03T21:59:10.000Z (6 months ago)
- Last Synced: 2025-01-06T18:36:33.032Z (6 months ago)
- Topics: clone, json, primitives, serialization, stringify
- Language: TypeScript
- Homepage:
- Size: 674 KB
- Stars: 0
- Watchers: 3
- Forks: 0
- Open Issues: 1
-
Metadata Files:
- Readme: readme.md
Awesome Lists containing this project
README
# primitivify
deep copy data keeping only primitives in nested data structures. useful for serializing complex objects where you only care about the raw data contained within.
"primitive-ify"
[](https://www.typescriptlang.org)
[](https://github.com/semantic-release/semantic-release)## install
`npm install --save primitivify`
## usage
the best demonstration of the value of this module is exemplified from the tests!
```ts
import primitivify from "primitivify";
const dummyFn = () => {};
const complex = {
dummyFn,
a: {
b: {
c: setTimeout(() => {}, 0),
},
d: setInterval(dummyFn, 1e3),
},
b: [dummyFn, "wee", { e: "e" }],
};
t.deepEqual(
{
// observe how non-primitive datas are nulled away
dummyFn: null,
a: {
b: {
c: null,
},
d: null,
},
b: [null, "wee", { e: "e" }],
},
primitivify(complexObj),
"complex"
);
```primitivify is immutable--calls return deeply cloned values.
need a _custom_ serializer? use the 2nd argument, `onVisit`, to transform the current value being inspected:
```ts
primitivify(
{ a: () => {} },
v => typeof v === 'function' ? 'wee' : v)
)
// { a: 'wee' }
```### why
generally to decomplect objects and/or arrays. consinder a simple example:
```js
JSON.stringify({ usefulData: "beep", a: setTimeout(() => {}, 0) });/*
Thrown:
TypeError: Converting circular structure to JSON
--> starting at object with constructor 'Timeout'
| property '_idlePrev' -> object with constructor 'TimersList'
--- property '_idleNext' closes the circle
at JSON.stringify ()
*/JSON.stringify(primitivify({ a: setTimeout(() => {}, 0) }));
/*
'{"usefulData":"beep","a":null}'
*/
```