Search code examples
javascriptjsonobjectmutate

JS: Check for existence of deep object key and replace value


I am wanting to develop a function to check for the existence of a key within a deep object and then replace the value of that key with a data set from another object.

E.g.

var obj = {
    "id": 1,
    "component": "Preset 1",
    "priority": 1,

    "header": {
        "modeSet": 2
    }
}

const modeSets = [
    {
        "id": 1
        "name": "Mode Set 1"
    },
    {
        "id": 2
        "name": "Mode Set 2"
    }
]

function obtainModeSets(obj){
   //...
}

When the function obtainModeSets runs I'd like to mutate obj so that the value of modeSet within obj equals { "id": 2 "name": "Mode Set 2" }

Does anyone have any suggestions? Thanks


Solution

  • You can use recursion like this

    const obj = {
      "id": 1,
      "component": "Preset 1",
      "priority": 1,
    
      "header": {
        "modeSet": 2
      }
    }
    
    const modeSets = [{
        "id": 1,
        "name": "Mode Set 1"
      },
      {
        "id": 2,
        "name": "Mode Set 2"
      }
    ]
    
    function obtainModeSets(obj) {
      Object.entries(obj).forEach(([key, value]) => {
        if (key === "modeSet") {
          obj[key] = modeSets.find(set => set.id === value)
          return
        }
    
        if (typeof value === "object") {
          obtainModeSets(value)
        }
      })
    }
    
    obtainModeSets(obj)
    
    console.log(obj)