Dưới đây là mã để hợp nhất (merge) nhiều đối tượng trong mảng thành một đối tượng đơn.
Ví dụ
<!DOCTYPE html> <html lang="vi"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Merge objects</title> <style> body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; } .result,.sample { font-size: 18px; font-weight: 500; color: rebeccapurple; } .sample { color: red; } </style> </head> <body> <h1>Hợp nhất đối tượng thành mảng đối tượng đơn</h1> <div class="sample"> [{id:22, class:7},{name:'Rohan', age:12},{state:'Delhi',country:'India'}] </div> <div class="result"><br /></div> <button class="Btn">NHẤN VÀO ĐÂY</button> <h3>Nhấn nút để hợp nhất các đối tượng trong mảng thành một đối tượng</h3> <script> let resEle = document.querySelector(".result"); let BtnEle = document.querySelector(".Btn"); let personObj = [ { id: 22, class: 7 }, { name: "Rohan", age: 12 }, { state: "Delhi", country: "India" }, ]; BtnEle.addEventListener("click", () => { personObj = Object.assign(...personObj); for (let i in personObj) { resEle.innerHTML += "key = " + i + " : Value = " + personObj[i] + "<br>"; } }); </script> </body> </html>
Kết quả
Khi nhấn nút, hiển thị đối tượng hợp nhất:
- key = id : Value = 22
- key = class : Value = 7
- key = name : Value = Rohan
- key = age : Value = 12
- key = state : Value = Delhi
- key = country : Value = India
Object.assign(...personObj) dùng spread operator để truyền từng đối tượng trong mảng làm source objects vào target rỗng (ngầm tạo object mới). Thứ tự sau ghi đè trước nếu trùng key.