I want to serialize an object o
, which has a method called, let’s say, a
. The object also holds a variable, which name is _a
.
I now want to parse this object to a JSON string. But the JSON looks something like this:
{
"_a": "",
...
}
Question
Is there a way, to comfortably remove/ replace the _
character(s) (or any character(s)).
What I have tried
- The rename parameter of the JSON.stringify() method.
1.1. Didn’t work, because you can only return altered values and no keys. - Iterating all keys of an object, deleting them and creating a new renamed key, and assigning the value (see code below).
2.1. This works, but is not really readable and nasty, when having “sub-object”.
Object.keys(o).forEach(key => {
Object.defineProperty(o, key.replace("_", ""),
Object.getOwnPropertyDescriptor(o, key));
delete o[key];
});