NodeJS Replace all values of a defined key in a json file

Viewed 85

im trying to go from this:

{
   "Level":"A",
   "Group LVL2":{
      "Level":"B",
      "Group LVL3":{
         "Level":"C"
}}}

To This

{
   "Level":"C",
   "Group LVL2":{
      "Level":"C",
      "Group LVL3":{
         "Level":"C"
}}}

So i basically want to replace all values of a json key to be the same. This a part of the code im using:

const fs = require('fs');
const fileName = './' + (Profile) + ".json";
const file = require(fileName);
const key = (Root);
file[Root] = (Value);

fs.writeFile(fileName, JSON.stringify(file, null, 2), function writeJSON(error) {
if (error) return console.log(error);

But it only replaces the Level Value of the first json group/line:

{
   "Level":"THIS WILL BE REPLACED",
   "Group LVL2":{
      "Level":"THIS WILL NOT BE REPLACED",
      "Group LVL3":{
         "Level":"THIS WILL NOT BE REPLACED"
      }
   }
}

Hope i can find a solution to this, i count on you! (There doesn't seem to be any beginner friendly solution online)

1 Answers

Below is the general solution for this kind of problem, maybe you can make it more efficient depending on your problem. It loops through all keys of the object that are nested objects themselves, recurses for each object in the json and updates the "Level" key.

function replaceValues(obj) {
    if(obj.hasOwnProperty(key))
        obj[key] = value;
    for (let property of Object.keys(obj)) {    
        if (typeof(obj[property]) === "object") {
           replaceValues(obj[property]);
        }
    }
}

Tested on the data you provided with Value = "D"

{
  "Level": "D",
  "Group LVL2": {
    "Level": "D",
    "Group LVL3": {
      "Level": "D"
    }
  }
}
Related