नेस्टेड ऑब्जेक्ट में for...in लूप या रिकर्सिव फंक्शन से विशिष्ट मान वाली कुंजी ढूंढें।
डेटा
const details = {
"teacherDetails": {
"teacherName": ["John", "David"]
},
"subjectDetails": {
"subjectName": ["MongoDB", "Java"]
}
};
विधि 1: नेस्टेड for...in लूप
const searchValue = "Java";
let foundKey = null;
let foundParentKey = null;
for (const parentKey in details) {
const nested = details[parentKey];
for (const childKey in nested) {
if (nested[childKey].includes(searchValue)) {
foundParentKey = parentKey;
foundKey = childKey;
break;
}
}
if (foundKey) break;
}
console.log(`${foundParentKey}, ${foundKey}`);
// "subjectDetails, subjectName"
विधि 2: Object.entries + find (मॉडर्न)
function findKeyPath(obj, searchValue) {
for (const [parentKey, parentVal] of Object.entries(obj)) {
for (const [childKey, childVal] of Object.entries(parentVal)) {
if (Array.isArray(childVal) && childVal.includes(searchValue)) {
return { parentKey, childKey };
}
}
}
return null;
}
console.log(findKeyPath(details, "Java"));
// { parentKey: 'subjectDetails', childKey: 'subjectName' }
विधि 3: रिकर्सिव (किसी भी गहराई के लिए)
function findKeyDeep(obj, target, path = []) {
if (obj === null || typeof obj !== 'object') return null;
// ऐरे में खोजें
if (Array.isArray(obj)) {
if (obj.includes(target)) return path;
return null;
}
// ऑब्जेक्ट की कुंजियों में खोजें
for (const [key, value] of Object.entries(obj)) {
const result = findKeyDeep(value, target, [...path, key]);
if (result) return result;
}
return null;
}
console.log(findKeyDeep(details, "Java"));
// [ 'subjectDetails', 'subjectName' ]
console.log(findKeyDeep(details, "David"));
// [ 'teacherDetails', 'teacherName' ]
विधि 4: फ्लैट मैप (सरल मामलों के लिए)
const entries = Object.entries(details).flatMap(([parentKey, parentVal]) =>
Object.entries(parentVal).map(([childKey, childVal]) => ({
parentKey, childKey, value: childVal
}))
);
const found = entries.find(e => e.value.includes("Java"));
console.log(found); // { parentKey: 'subjectDetails', childKey: 'subjectName', value: [...] }
चलाने का तरीका
node nested-object-key.js
आउटपुट
subjectDetails, subjectName
सारांश
| विधि | उपयोग केस |
|---|---|
| नेस्टेड for...in | ज्ञात 2-लेवल स्ट्रक्चर |
| Object.entries + find | क्लीनर, मॉडर्न |
| रिकर्सिव | अज्ञात/चर गहराई |
| flatMap | वन-लाइनर, सिंपल स्ट्रक्चर |