Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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" }

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading