JavaScriptオブジェクトを新しい配列にフォーマットする
以下は、JavaScriptオブジェクトを新しい配列にフォーマットするためのコードです-
例
<!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>
出力
上記のコードは次の出力を生成します-
[ここをクリック]ボタンをクリックすると-
-
JavaScriptのObject.keys()。map()VS Array.map()
以下は、JavaScriptでObject.keys()。map()とArray.map()を示すコードです- 例 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title>
-
JavaScriptでオブジェクトプロパティ名の配列を置き換える
以下は、JavaScriptでオブジェクトプロパティ名の配列を置き換えるコードです- 例 <!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&g