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

Time:12-17

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

CodePudding user response:

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).map(([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)

CodePudding user response:

I think something like the below code maybe solves your problem. I don't know what you mean exactly. But based on the showing example, I guess you need to replace your key with the id provided in the modeSets.

function obtainModeSets(obj, key, cb){
  // loop through all possible keys
  Object.keys(obj).forEach(k => {
    if (key === k) {
      obj[k] = cb(obj[k])
    }

    // if the value of the key is object, just go inside
    if (typeof obj[k] === "object") {
      obtainModeSets(obj[k], key, cb)
    }
  })
}

// you can call your function like this
obtainModeSets(obj, 'modeSet', (val) => {
  return modeSets.find(mode => mode.id === val)
})
  • Related