다음과 같은 복잡한 JSON 객체가 있다고 가정해 보겠습니다. -
const obj = {
"id": "0001",
"fieldName": "sample1",
"fieldValue" "0001",
"subList": [
{
"id": 1001,
"fieldName": "Sample Child 1",
"fieldValue": "1001",
"subList": []
},
{
"id": 1002,
"fieldName": "Sample Child 2",
"fieldValue": "1002",
"subList": []
}
]
} 우리는 하나의 그러한 객체와 키 값 쌍(필수적으로 "id" 키-값 쌍)을 취하는 JavaScript 함수를 작성해야 합니다. 그런 다음 함수는 쿼리된 키/값 쌍을 포함하는 전체 하위 개체를 반환해야 합니다.
예시
이에 대한 코드는 -
const obj = {
"id": "0001",
"fieldName": "sample1",
"fieldValue": "0001",
"subList": [
{
"id": 1001,
"fieldName": "Sample Child 1",
"fieldValue": "1001",
"subList": []
},
{
"id": 1002,
"fieldName": "Sample Child 2",
"fieldValue": "1002",
"subList": []
}
]
}
function searchById(searchKey, obj) {
let key = Object.keys(searchKey)[0];
let res;
if (obj[key] === searchKey[key]) {
return obj;
};
obj.subList.some(function (a) {
res = searchById(searchKey, a);
return res;
});
return res;
}
console.log(searchById({id: 1002}, obj)); 출력
콘솔의 출력은 -
{
id: 1002,
fieldName: 'Sample Child 2',
fieldValue: '1002',
subList: []
}