Search a complex object by id property in JavaScript


Suppose we have a complex JSON Object like this −

const obj = {
   "id": "0001",
   "fieldName": "sample1",
   "fieldValue" "0001",
   "subList": [
      {
         "id": 1001,
         "fieldName": "Sample Child 1",
         "fieldValue": "1001",
         "subList": []
      },
      {
         "id": 1002,
         "fieldName": "Sample Child 2",
         "fieldValue": "1002",
         "subList": []
      }
   ]
}

We are required to write a JavaScript function that takes in one such object and a key value pair (necessarily an "id" key-value pair). Then the function should return the whole sub object that contains the queried key/value pair.

Example

The code for this will be −

const obj = {
   "id": "0001",
   "fieldName": "sample1",
   "fieldValue": "0001",
   "subList": [
      {
         "id": 1001,
         "fieldName": "Sample Child 1",
         "fieldValue": "1001",
         "subList": []
      },
      {
         "id": 1002,
         "fieldName": "Sample Child 2",
         "fieldValue": "1002",
         "subList": []
      }
   ]
}
function searchById(searchKey, obj) {
   let key = Object.keys(searchKey)[0];
   let res;
   if (obj[key] === searchKey[key]) {
      return obj;
   };
   obj.subList.some(function (a) {
      res = searchById(searchKey, a);
      return res;
   });
   return res;
}
console.log(searchById({id: 1002}, obj));

Output

And the output in the console will be −

{
   id: 1002,
   fieldName: 'Sample Child 2',
   fieldValue: '1002',
   subList: []
}

Updated on: 20-Nov-2020

276 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements