Duyệt object lồng nhau bằng vòng lặp for...in lồng nhau, dùng includes() kiểm tra giá trị trong mảng.
Ví dụ
var details = {
"teacherDetails": {
"teacherName": ["John", "David"]
},
"subjectDetails": {
"subjectName": ["MongoDB", "Java"]
}
};
var searchValue = "Java";
var parentKey, childKey;
for (var key1 in details) {
for (var key2 in details[key1]) {
if (details[key1][key2].includes(searchValue)) {
parentKey = key1;
childKey = key2;
}
}
}
console.log(parentKey + ", " + childKey);
Cách chạy
node demo.js
Kết quả
subjectDetails, subjectName
Cách hiện đại (ES2017+):
const entries = Object.entries(details).flatMap(([k1, v1]) =>
Object.entries(v1).map(([k2, v2]) => [k1, k2, v2])
);
const found = entries.find(([_, __, arr]) => arr.includes(searchValue));
console.log(found ? `${found[0]}, ${found[1]}` : 'Not found');