Để in mảng đối tượng ra màn hình hoặc console dễ đọc, sử dụng phương thức JSON.stringify().
Ví dụ
<!DOCTYPE html>
<html>
<body>
<pre id="ketQua"></pre>
<script>
var data = [
{ date: new Date(2017, 11, 25), value: 10 },
{ date: new Date(2017, 11, 30), value: 20 }
];
// Tham số 3: null (replacer), 4 (khoảng thụt lề - indent)
document.getElementById('ketQua').innerHTML = JSON.stringify(data, null, 4);
</script>
</body>
</html>
Kết quả
[
{
"date": "2017-12-24T18:30:00.000Z",
"value": 10
},
{
"date": "2017-12-29T18:30:00.000Z",
"value": 20
}
]
Tham số của JSON.stringify(value, replacer, space):
- value: Giá trị cần chuyển đổi.
- replacer (tùy chọn): Hàm hoặc mảng để lọc/transform thuộc tính.
- space (tùy chọn): Số khoảng trắng để thụt lề (định dạng pretty-print).
Mẹo: Dùng console.log(JSON.stringify(data, null, 2)) trong DevTools để debug nhanh.