-1

I have JSON data coming from the API and I want to rename occurrences of the multiple keys. I have tried multiple approaches but no luck so far.

Here's what my data look like roughly

{
   "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
      }
   }
}

In the provided data, I would like to change all the instances of "Amazon Simple Storage Service" to "S3" and "Amazon Elastic Compute Cloud - Compute" to "EC2". What are the possible ways I can modify the nested data inside the object?

To work around that, I tried to modify the DOM with custom JS something like:

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

It's working as expected but since I am passing the object to chart JS it's not updating the occurrences on the Chart.

Any guide/help would be highly appreciated.

Muhaddis
  • 530
  • 7
  • 18
  • 2
    A "no brainer" solution would be to stringify the JSON, use the `replace` function of strings and then parse it back to JSON. – Enak May 28 '21 at 10:55
  • Maybe this can help you out https://stackoverflow.com/questions/10684695/what-javascript-object-to-object-mapping-libraries-exist – Nissan May 28 '21 at 11:05
  • [How much research effort is expected of Stack Overflow users?](https://meta.stackoverflow.com/questions/261592/how-much-research-effort-is-expected-of-stack-overflow-users) – Andreas May 28 '21 at 11:12

1 Answers1

0

This should work.

JSON.parse(JSON.stringify(yourObject).replace(/Amazon Simple Storage Service/g, "S3").replace(/Amazon Elastic Compute Cloud - Compute/g, "EC2"))
Prayag Choraria
  • 710
  • 5
  • 15
  • 1
    That's a terrible idea which will instantly break when there's a property with a partial match. – Andreas May 28 '21 at 11:08
  • My solution is not meant to be generic. It serves the current purpose and if ever required the `regex` can be tweaked to get the desired result. So, it's not a terrible idea. – Prayag Choraria May 28 '21 at 11:17