ต่อไปนี้เป็นรหัสสำหรับจัดรูปแบบวัตถุ JavaScript เป็น Array ใหม่ -
ตัวอย่าง
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; } .result { font-size: 18px; font-weight: 500; color: rebeccapurple; } </style> </head> <body> <h1>Formatting JavaScript Object to new Array.</h1> <div class="result"></div> <button class="Btn">CLICK HERE</button> <h3>Click on the above button to format the school object to an array</h3> <script> const school = { name: "St Marks", address: "Delhi", students: [ { firstName: "Rohan", lastName: "Sharma", age: 14, }, { firstName: "Mohit", lastName: "Singh", age: 18, }, { firstName: "Mike", lastName: "Shaw", age: 17, }, { firstName: "Roy", lastName: "Mehta", age: 16, }, ], }; let resEle = document.querySelector(".result"); let schoolArr = []; let { name, address } = school; for (let student of school.students) { schoolArr.push( `${student.firstName} ${student.lastName} ${student.age}` ); } document.querySelector(".Btn").addEventListener("click", () => { schoolArr.forEach((item) => { resEle.innerHTML += item + "<br>"; }); }); </script> </body> </html>
ผลลัพธ์
รหัสข้างต้นจะสร้างผลลัพธ์ต่อไปนี้ -
เมื่อคลิกปุ่ม 'คลิกที่นี่' -