다음과 같은 중첩된 JSON 객체가 있다고 가정해 보겠습니다. -
const obj = {
"prop": [
{
"key": "FOO",
"value": "Foo is wonderfull, foo is great"
},
{
"key": "BAR",
"value": "Bar is bad, really bad"
}
]
}; 이러한 객체를 첫 번째 인수로, 키 문자열을 두 번째 인수로 취하는 JavaScript 함수를 작성해야 합니다.
그러면 우리 함수는 특정 키 속성이 속한 "값" 속성에 대한 값을 반환해야 합니다.
예시
이에 대한 코드는 -
const obj = {
"prop": [
{
"key": "FOO",
"value": "Foo is wonderfull, foo is great"
},
{
"key": "BAR",
"value": "Bar is bad, really bad"
}
]
};
const findByKey = (obj, key) => {
const arr = obj['prop'];
if(arr.length){
const result = arr.filter(el => {
return el['key'] === key;
});
if(result && result.length){
return result[0].value;
}
else{
return '';
}
}
}
console.log(findByKey(obj, 'BAR')); 출력
콘솔의 출력은 -
Bar is bad, really bad