Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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: []
}Advertisements