मान लीजिए हमारे पास ऐसा ऑब्जेक्ट है -
const obj = {
"name": "Vivek Sharma",
"occupation": "Software Engineer",
"age": 23,
"contacts": [{
"name": "Mukul Sharma",
"occupation": "Software Engineer",
"age": 31,
}, {
"name": "Jay Sharma",
"occupation": "Software Engineer",
"age": 27,
}, {
"name": "Rajan Sharma",
"occupation": "Software Engineer",
"age": 32,
}]
};यहां यह केवल एक लेवल तक नेस्टेड है, लेकिन नेस्टिंग गहरी भी हो सकती है। हमें एक ऑब्जेक्ट फ़ंक्शन Object.prototype.keysOf() लिखना होगा जो एक वैल्यू लेता है और उन सभी कीज़ का ऐरे लौटाता है जिनके पास आर्गुमेंट में निर्दिष्ट वैल्यू है।
आइए अब इस फ़ंक्शन के लिए कोड लिखते हैं।
उदाहरण
const obj = {
"name": "Vivek Sharma",
"occupation": "Software Engineer",
"age": 23,
"contacts": [{
"name": "Mukul Sharma",
"occupation": "Software Engineer",
"age": 31,
}, {
"name": "Jay Sharma",
"occupation": "Software Engineer",
"age": 27,
}, {
"name": "Rajan Sharma",
"occupation": "Software Engineer",
"age": 32,
}]
};
const keysOf = function(val, obj = this, res = []){
const keys = Object.keys(obj);
for(let ind = 0; ind < keys.length; ind++){
if(obj[keys[ind]] === val){
res.push(keys[ind]);
}else if(typeof obj[keys[ind]] === 'object' &&
!Array.isArray(obj[keys[ind]])){
keysOf(val, obj[keys[ind]], res);
};
};
return res;
};
Object.prototype.keysOf = keysOf;
console.log(obj.keysOf(23));आउटपुट
कंसोल में आउटपुट होगा -
['age']