简体   繁体   English

json.stringify object 并重命名 json 中的变量

[英]json.stringify object and rename variables in json

I want to serialize an object o , which has a method called, let's say, a .我想序列化一个 object o ,它有一个名为a的方法。 The object also holds a variable, which name is _a . object 还包含一个变量,其名称为_a

I now want to parse this object to a JSON string.我现在想将此 object 解析为 JSON 字符串。 But the JSON looks something like this:但是 JSON 看起来像这样:

{
    "_a": "",
    ...
}

Question问题

Is there a way, to comfortably remove/ replace the _ character(s) (or any character(s)).有没有办法轻松删除/替换_字符(或任何字符)。

What I have tried我试过的

  1. The rename parameter of the JSON.stringify() method. JSON.stringify() 方法的重命名参数。
    1.1. 1.1。 Didn't work, because you can only return altered values and no keys.没用,因为您只能返回更改后的值而没有键。
  2. Iterating all keys of an object, deleting them and creating a new renamed key, and assigning the value (see code below).迭代 object 的所有键,删除它们并创建一个新的重命名键,然后分配值(参见下面的代码)。
    2.1. 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];
});

Would something like this work for you:像这样的东西对你有用吗:

 let obj = { "_a": "", "b": "Test" } let result = Object.entries(obj).reduce((acc, [key, value]) => { let newKey = key.replace('_', '') acc[newKey] = value return acc }, {}) console.log(result)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM