Home > Software engineering >  Deep search is object in javascript
Deep search is object in javascript

Time:05-11

I am trying to search any pairs key:value in an object in JavaScript, and return the sub-object it belongs to.

What I have done so far doesn’t return my object as expected and I can’t find why.

function searchSheet(obj, keyName, valName) {
  let found
  for (prop in obj) {
    if (typeof obj[prop] == "object") {
      searchSheet(obj[prop], keyName, valName);
    } else {
      if (prop === keyName && obj[prop] === valName) {
        found = obj
        console.log(found);
        // found is logged correctly here
        return found
        // …but nothing is returned here
      }
    }
  }
}
let sheet = {
  "config": {},
  "patterns": {
    "id": 0,
    "type": "pattern",
    "startTime": 1652193369859,
    "synth": "tic",
    "keys": [{
        "id": 1,
        "type": "key",
        "keyCode": 73,
        "startTime": 1652193369960,
        "note": 730,
        "offset": "12.1"
      },
      {
        "id": 2,
        "type": "key",
        "keyCode": 82,
        "startTime": 1652193370371,
        "note": 820,
        "offset": "61.2"
      }
    ],
    "endTime": 1652193370695,
    "duration": 836,
    "loop": 35
  }
}
console.log(
  searchSheet(sheet, "keyCode", 82) // undefined
)  

CodePudding user response:

Ian Brindley's comment is partly correct. You are discarding the return value of the recursive call. You can fix your code by changing this

if (typeof obj[prop] == "object") {
  searchSheet(obj[prop], keyName, valName);
} else { //...

to this

if (typeof obj[prop] == "object") {
   let objectFound = searchSheet(obj[prop], keyName, valName);
   if (objectFound !== undefined) return objectFound
} else { //...

There are other approaches, particularly ones using a nested helper function.

  • Related