【问题标题】:How to rename the keys of nested object in Javascript? [duplicate]如何在Javascript中重命名嵌套对象的键? [复制]
【发布时间】:2021-08-16 14:56:41
【问题描述】:

我有来自 API 的 JSON 数据,我想重命名多个键的出现。我尝试了多种方法,但到目前为止都没有运气。

我的数据大致如下所示

{
   "9ba698a4-d54c-448c-a216-10d52ed2a5a5":{
      "name":"x",
      "data":{
         "2021-05-04":{
            "Amazon Simple Storage Service":123,
            "Amazon Elastic Compute Cloud - Compute":123,
            "sum":123,
            "credits":{
               "total":-123,
               "Amazon Simple Storage Service":-123,
               "Amazon Elastic Compute Cloud - Compute":-123
            }
         },
         "2021-05-07":{
            "Amazon Simple Storage Service":123,
            "Amazon Elastic Compute Cloud - Compute":123,
            "sum":123,
            "credits":{
               "total":-123,
               "Amazon Simple Storage Service":-123,
               "Amazon Elastic Compute Cloud - Compute":-123
            }
         },
         "services":[
            "Amazon Simple Storage Service",
            "Amazon Elastic Compute Cloud - Compute"
         ],
         "total":123,
         "credits_total":-123
      }
   }
}

在提供的数据中,我想将“Amazon Simple Storage Service”的所有实例更改为“S3”,将“Amazon Elastic Compute Cloud - Compute”的所有实例更改为“EC2”。我可以通过哪些方式修改对象内的嵌套数据?

为了解决这个问题,我尝试使用自定义 JS 修改 DOM,例如:

document.body.innerHTML = document.body.innerHTML.replace("Amazon Elastic Compute Cloud - Compute", "S3");

它按预期工作,但由于我将对象传递给图表 JS,它没有更新图表上的出现。

任何指南/帮助将不胜感激。

【问题讨论】:

标签: javascript arrays json reactjs


【解决方案1】:

这应该可行。

JSON.parse(JSON.stringify(yourObject).replace(/Amazon Simple Storage Service/g, "S3").replace(/Amazon Elastic Compute Cloud - Compute/g, "EC2"))

【讨论】:

  • 这是一个糟糕的想法,当有一个部分匹配的属性时会立即中断。
  • 我的解决方案并不是通用的。它服务于当前目的,如果需要,可以调整 regex 以获得所需的结果。所以,这不是一个糟糕的主意。
猜你喜欢
  • 1970-01-01
  • 2019-04-11
  • 1970-01-01
  • 1970-01-01
  • 2020-01-17
  • 2021-10-23
  • 1970-01-01
  • 2011-06-06
  • 1970-01-01
相关资源
最近更新 更多