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
Find specific key value in array of objects using JavaScript
Suppose we have a JSON object like this −
const obj = {
"LAPTOP": [{
"productId": "123"
}],
"DESKTOP": [{
"productId": "456"
}],
"MOUSE": [{
"productId": "789"
}, {
"productId": "012"
}],
"KEY-BOARD": [{
"productId": "345"
}]
};
We are required to write a JavaScript function that takes in one such object as the first argument, and a key value pair as the second argument.
The key value pair is basically nothing but an object like this −
const pair = {"productId": 456};
The function should then search the object for the key with specified "productId" and return that.
Example
The code for this will be −
const obj = {
"LAPTOP": [{
"productId": "123"
}],
"DESKTOP": [{
"productId": "456"
}],
"MOUSE": [{
"productId": "789"
}, {
"productId": "012"
}],
"KEY-BOARD": [{
"productId": "345"
}]
};
const searchByPair = (obj = {}, pair = {}) => {
const toSearch = Object.values(pair)[0];
let required = undefined;
Object.keys(obj).forEach((key) => {
if(obj[key].find((pid) => pid.productId === toSearch)){
required = key;
}
});
return required;
};
console.log(searchByPair(obj, {
'productId': '123'
}));
Output
And the output in the console will be −
LAPTOP
Advertisements