Giả sử chúng ta có một mảng JSON với các đối tượng cặp khóa/giá trị như sau:
const arr = [{
"key": "name", "value": "john"
}, {
"key": "number", "value": "1234"
}, {
"key": "price", "value": [{
"item": [{
"item": [{
"key": "quantity", "value": "20"
}, {
"key": "price", "value": "200"
}]
}]
}]
}];
Chúng ta cần viết một hàm JavaScript nhận một mảng như vậy.
Hàm sẽ chuẩn bị một mảng mới nơi dữ liệu đơn giản được liệt kê theo khóa giá trị thay vì cấu trúc phức tạp này.
Do đó, với mảng trên, đầu ra sẽ trông như:
const output = {
"name": "john",
"number": "1234",
"price": { "quantity": "20", "price": "200" }
};
Ví dụ
Mã thực hiện:
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));
Kết quả
Kết quả trong console:
{
name: 'john',
number: '1234',
price: { quantity: '20', price: '200' }
}