Canop / JSON.prune

A pruning version of JSON.stringify, allowing for example to stringify window or any big or recursive object
MIT License
163 stars 27 forks source link

please support regexp #11

Closed luckylooke closed 4 years ago

luckylooke commented 4 years ago

Thank you for sharing! Could you please support regexps?

JSON.prune({regexp: /abc123/});
"{"regexp":{}}"

expecting value same as from /abc123/.toString()

JSON.prune({regexp: /abc123/});
"{"regexp":"/abc123/"}"

Even better if you support also keyed collections, I mostly use maps

JSON.prune({map: new Map([
  [1, 'one'],
  [2, 'two'],
  [3, 'three'],
])});
"{"map":{}}"

can be stringified by

let myMap = new Map([
  [1, 'one'],
  [2, 'two'],
  [3, 'three'],
]);
JSON.stringify(myMap, (key, value) => (value instanceof Map ? [...value] : value));
"[[1,"one"],[2,"two"],[3,"three"]]"

Many thanks :)

Canop commented 4 years ago

This looks reasonable.

GrosSacASac commented 4 years ago

A map can also be cast to an object and back if keys are strings only

let asObject = Object.fromEntries(myMap);
let map = new Map(Object.entries(asObject));

As an alternative to the syntax [...value] consider Array.from that accepts an argument to map over keys, values to have a chance to prune them as well.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from

luckylooke commented 4 years ago

@GrosSacASac actualy map can have anything as keys.. so maybe it could be implemented somehow safely.. with type check or something.

I was even wondering that functions are cleared from result but there could be referenced somehow... for example you have access to function name if it is defined, so maybe in result there could be some notice that there was function with name "xyz".

I wanted to use this lib to see webpack configuration in my project.. because it is somehow directed by framework... but I have found that vue cli have command for it "vue inspect" so I was able to put it in a file and read (vue inspect > webpack_cfg.txt) 💪🙂

Anyway I find this lib very useful and I am sure I will use it in the future, thank you for sharing! 👍