다음과 같은 키/값 쌍 객체가 있는 JSON 배열이 있다고 가정합니다.
const arr = [{
"key": "name",
"value": "john"
},
{
"key": "number",
"value": "1234"
},
{
"key": "price",
"value": [{
"item": [{
"item": [{
"key": "quantity",
"value": "20"
},
{
"key": "price",
"value": "200"
}]
}]
}]
}]; 이러한 배열을 취하는 JavaScript 함수를 작성해야 합니다.
함수는 이러한 복잡한 구조 대신 키 값에 대해 단순히 데이터가 나열되는 새 배열을 준비해야 합니다.
따라서 위 배열의 경우 출력은 다음과 같아야 합니다. -
const output = {
"name": "john",
"number": "1234",
"price": {
"quantity": "20",
"price": "200"
}
}; 예시
이에 대한 코드는 -
const arr = [{
"key": "name",
"value": "john"
},
{
"key": "number",
"value": "1234"
},
{
"key": "price",
"value": [{
"item": [{
"item": [{
"key": "quantity",
"value": "20"
},
{
"key": "price",
"value": "200"
}]
}]
}]
}];
const simplify = (arr = []) => {
const res = {};
const recursiveEmbed = function(el){
if ('item' in el) {
el.item.forEach(recursiveEmbed, this);
return;
};
if (Array.isArray(el.value)) {
this[el.key] = {};
el.value.forEach(recursiveEmbed, this[el.key]);
return;
};
this[el.key] = el.value;
};
arr.forEach(recursiveEmbed, res);
return res;
};
console.log(simplify(arr)); 출력
콘솔의 출력은 -
{
name: 'john',
number: '1234',
price: { quantity: '20', price: '200' }
}