Giả sử sau đây là Bộ của chúng tôi -
var name = new Set(['John', 'David', 'Bob', 'Mike']);
Để chuyển đổi tập hợp thành đối tượng, hãy sử dụng Object.assign () trong JavaScript -
var setToObject = Object.assign({}, ...Array.from(name, value => ({ [value]: 'not assigned' }))); Ví dụ
Sau đây là mã -
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); Để chạy chương trình trên, bạn cần sử dụng lệnh sau -
node fileName.js.
Đây, tên tệp của tôi là demo260.js.
Đầu ra
Điều này sẽ tạo ra kết quả sau trên bảng điều khiển -
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'
}