Giả sử chúng ta có Set sau:
var name = new Set(['John', 'David', 'Bob', 'Mike']);
Để chuyển đổi Set thành Object, hãy sử dụng Object.assign() trong JavaScript:
var setToObject = Object.assign({}, ...Array.from(name, value => ({ [value]: 'not assigned' })));Ví dụ
Mã hoàn chỉnh:
var name = new Set(['John', 'David', 'Bob', 'Mike']);
var setToObject = Object.assign({}, ...Array.from(name, value => ({ [value]: 'not assigned' })));
console.log("Kết quả Set =");
console.log(name);
console.log("Kết quả Object =");
console.log(setToObject);Để chạy chương trình, sử dụng lệnh:
node tenFile.js
Tên file ở đây là demo260.js.
Kết quả
Đầu ra trên console:
PS C:\Users\Amit\javascript-code> node demo260.js
Kết quả Set = Set { 'John', 'David', 'Bob', 'Mike' }
Kết quả Object = { John: 'not assigned', David: 'not assigned', Bob: 'not assigned', Mike: 'not assigned' }