Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

การวนลูป JSON array ใน JavaScript

คำอธิบาย

ใช้ JSON.parse() แปลงสตริง JSON ในอาร์เรย์เป็นออบเจกต์จริง แล้ววนลูป

ตัวอย่างโค้ด

var apiValues = [
  '{"name": "John", "scores": [78, 89]}',
  '{"name": "David", "scores": [58, 98]}',
  '{"name": "Bob", "scores": [56, 79]}',
  '{"name": "Mike", "scores": [94, 91]}'
];

var parseJSONObject = apiValues.map(obj => JSON.parse(obj));
console.log("The original String:", apiValues);
console.log("The JSON Objects:", parseJSONObject);

วิธีรัน

node fileName.js

ผลลัพธ์

The JSON Objects: [
  { name: 'John', scores: [ 78, 89 ] },
  { name: 'David', scores: [ 58, 98 ] },
  { name: 'Bob', scores: [ 56, 79 ] },
  { name: 'Mike', scores: [ 94, 91 ] }
]