Search code examples
javascriptnode.jsjsonlodash

How to find and replace value in JSON?


I have an object like this:

{
  "responses": {
    "firstKey": {
      "items": {
        "name": "test name one"
      }
    },
    "anotherKey": {
      "items": {
        "name": "test name two"
      }
    },
    "oneMoreKey": {
      "items": {
        "name": "John"
      }
    }
  }
}

I need to find all 'name' keys and replace its value only if it starts with 'test name' then return new JSON object:

{
  "responses": {
    "firstKey": {
      "items": {
        "name": "N/A"
      }
    },
    "anotherKey": {
      "items": {
        "name": "N/A"
      }
    },
    "oneMoreKey": {
      "items": {
        "name": "John"
      }
    }
  }
}

The problem is that the keys are not consistent through the objects, i.e. 'firstKey', 'secondKey'... I tried ForEach but it seems to be too cumbersome... So I need either lodash or vanila JavaScript to replace the values.


Solution

  • Do something like this. Convert to string replace using regex (add key to regex as well) and then convert back.

    
    var data = {
      "responses": {
        "firstKey": {
          "items": {
            "name": "test name one"
          }
        },
        "anotherKey": {
          "items": {
            "name": "test name two"
          }
        },
        "oneMoreKey": {
          "items": {
            "name": "John"
          }
        }
      }
    };
    
    var originalMsg = JSON.stringify(data);
    console.log(data)
    console.log(originalMsg)
    var updatedMsg = originalMsg.replace(/test name [a-z]*/g, "N/A");
    console.log(updatedMsg)
    var newObj = JSON.parse(updatedMsg); 
    console.log(newObj);