다음과 같은 객체가 있다고 가정합니다. -
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 함수 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']