Test if a key-value pair exists in nested object in Typescript I wrote a function to check if a nested object contains the key-value pair matched as parameter as following.
eq:
const obj ={
   &quot;a&quot;:{
      &quot;b&quot;:{
         &quot;c1&quot;:[&quot;1&quot;,&quot;2&quot;],
         &quot;c2&quot;:&quot;3&quot;
      },
      &quot;b2&quot;:&quot;values&quot;,
      &quot;b3&quot;: {&quot;c5&quot;: &quot;v&quot;},
   },
   &quot;a2&quot;:[&quot;v1&quot;,&quot;v2&quot;],
   &quot;a3&quot;:&quot;v1&quot;
}
checkNestedObjectByKeyValue(obj, &quot;a3&quot;, &quot;v1&quot;) // true
checkNestedObjectByKeyValue(obj, &quot;a3&quot;, &quot;v2&quot;) // false
checkNestedObjectByKeyValue(obj, &quot;a2&quot;, [&quot;v1&quot;,&quot;v2&quot;]) // true
checkNestedObjectByKeyValue(obj, &quot;a3&quot;, &quot;v1&quot;) // true
checkNestedObjectByKeyValue(obj, &quot;b3&quot;, {&quot;c5&quot;: &quot;v&quot;}) // true


function checkNestedObjectByKeyValue(
  obj: Record&lt;string, any&gt;,
  objKey: string,
  objValue: string | Array&lt;string&gt;
): boolean {

  if (typeof obj !== 'object') return false;
  if (obj.hasOwnProperty(objKey)) {

    return JSON.stringify(obj[objKey]) === JSON.stringify(objValue)
  }
  for (const value of Object.values(obj)) {
    if (checkNestedObjectByKeyValue(value, objKey, objValue)) return true
  }
  return false
}
Based on your description of the function, I would expect this test to return true, but your implementation returns false.  So, either your description is unclear, or your implementation is buggy.
const obj ={
   &quot;a&quot;:{
      &quot;b&quot;:{
         &quot;a3&quot;:&quot;v2&quot;,
         &quot;c1&quot;:[&quot;1&quot;,&quot;2&quot;],
         &quot;c2&quot;:&quot;3&quot;
      },
      &quot;b2&quot;:&quot;values&quot;,
      &quot;b3&quot;: {&quot;c5&quot;: &quot;v&quot;},
   },
   &quot;a2&quot;:[&quot;v1&quot;,&quot;v2&quot;],
   &quot;a3&quot;:&quot;v1&quot;
}
checkNestedObjectByKeyValue(obj, &quot;a3&quot;, &quot;v2&quot;) // false, but I would expect true