Search code examples
javascriptarraystraversal

I have to traverse a multilevel JSON and remove certain keys


I have a JSON shown below. I need to remove some of the keys mentioned in an array = ["field", "type", "input"]

const result = {
   "condition":"AND",
   "rules":[
      {
         "id":"search_across",
         "operator":"equal",
         "value":1
      },
      {
         "condition":"AND",
         "rules":[
            {
               "id":"Recipe ID",
               "field":"Recipe ID",
               "type":"string",
               "input":"text",
               "operator":"equal",
               "value":"100"
            },
            {
               "condition":"AND",
               "rules":[
                  {
                     "id":"Recipe ID",
                     "field":"Recipe ID",
                     "type":"string",
                     "input":"text",
                     "operator":"equal",
                     "value":"200"
                  }
               ]
            }
         ]
      }
   ]
}

I need to remove the keys for nth level. I was only able to remove it from the 1st level (as seen in the JSON)


Solution

  • You can create recursive function using for...in loop to delete property by key on any level.

    const data = {"condition":"AND","rules":[{"id":"search_across","operator":"equal","value":1},{"condition":"AND","rules":[{"id":"Recipe ID","field":"Recipe ID","type":"string","input":"text","operator":"equal","value":"100"},{"condition":"AND","rules":[{"id":"Recipe ID","field":"Recipe ID","type":"string","input":"text","operator":"equal","value":"200"}]}]}]}
    
    function remove(data, keys) {
      for(let i in data) {
        if(keys.includes(i)) delete data[i];
        else if(typeof data[i] === 'object') remove(data[i], keys)
      }
    }
    
    remove(data, ["field", "type", "input"])
    console.log(data)