Search code examples
javascriptecmascript-6ecmascript-5

Replace property of a nested object by matching its key


I have an object of the following kind

let obj = {
    "p1" : "main",
    "p2" : {
        "p21" : [
            {
                "key1" : "val1",
                "value1" : "val2",
            },
            {
                "prop"  : "test",
                "value" : "dummy"
            }
        ]
    }
}

Need to find the "prop", and if its present set the "value" to empty string. Note there might be any number objects inside "p21" and in any order. Just need to find "prop" and then update "value" to empty string

Have tried the following

obj.p2.p21.map((item) => {
    if (item.hasOwnProperty("prop")) {
      item.value = "";
    }
})


Solution

  • You need to create a function to check the key and then replace value.

    let obj = {
      "p1": "main",
      "p2": {
        "p21": [{
            "key1": "val1",
            "value1": "val2",
          },
          {
            "prop": "test",
            "value": "dummy"
          }
        ]
      }
    }
    
    function replaceValue(item) {
      for (var i in item) {
        if (i == "prop") {
          item["value"] = "";
          break;//break if you only want to place the first , otherwise remove it
        }
      }
    }
    
    obj.p2.p21.map(item => replaceValue(item));
    
    console.log(obj);
    .as-console {
      height: 100% !important;
    }