Convert set to object - JavaScript?

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

Let’s say the following is our Set −

var name = new Set(['John', 'David', 'Bob', 'Mike']);

To convert the set to object, use the Object.assign() in JavaScript −

var setToObject = Object.assign({}, ...Array.from(name, value => ({ [value]: 'not assigned' })));

Example

Following is the code −

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);

To run the above program, you need to use the following command −

node fileName.js.

Here, my file name is demo260.js.

Output

This will produce the following output on console −

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'
}
raja
Published on 09-Nov-2020 07:33:00
Advertisements