สมมติว่ามี Set ดังนี้:
var name = new Set(['John', 'David', 'Bob', 'Mike']);
เพื่อแปลง Set เป็น Object ให้ใช้ Object.assign() ร่วมกับ Array.from()
var setToObject = Object.assign({}, ...Array.from(name, value => ({ [value]: 'not assigned' })));ตัวอย่างโค้ด
var name = new Set(['John', 'David', 'Bob', 'Mike']);
var setToObject = Object.assign({}, ...Array.from(name, value => ({ [value]: 'not assigned' })));
console.log("The Set result=");
console.log(name);
console.log("The Object result=");
console.log(setToObject);รันด้วยคำสั่ง:
node fileName.js
ชื่อไฟล์: demo260.js
ผลลัพธ์
PS C:\Users\Amit\javascript-code> node demo260.js
The Set result= Set { 'John', 'David', 'Bob', 'Mike' }
The Object result= { John: 'not assigned', David: 'not assigned', Bob: 'not assigned', Mike: 'not assigned' }คำอธิบาย: Array.from() แปลง Set เป็นอาร์เรย์ แล้ว map แต่ละค่าเป็นออบเจ็กต์ {[value]: 'not assigned'} สุดท้าย Object.assign() รวมเป็นออบเจ็กต์เดียว