Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Convert set to object - JavaScript?
The task we are going to perform in this article is converting a JavaScript Set to an object. Before we jump into the methods, let's have a quick overview of Sets and objects in JavaScript.
A JavaScript Set is a collection of unique values where each value can only appear once. An object in JavaScript is a data structure with properties and values, similar to a dictionary or map. Converting Sets to objects is useful when you need to work with key-value pairs instead of just values.
There are several methods to convert a Set to an object in JavaScript. Let's explore the most effective approaches.
Method 1: Using Object.assign() with Array.from()
The Object.assign() method copies properties from source objects to a target object. Combined with Array.from(), it can convert Set values to object properties.
Syntax
Object.assign(target, ...sources)
Example
<!DOCTYPE html>
<html>
<body>
<p id="result1"></p>
<script>
const carBrands = new Set(['BMW', 'BENZ', 'AUDI', 'DUCATI']);
const result = Object.assign(...Array.from(carBrands, v => ({[v]: ''})));
document.getElementById("result1").innerHTML = JSON.stringify(result);
</script>
</body>
</html>
{"BMW":"","BENZ":"","AUDI":"","DUCATI":""}
Method 2: Using Array.reduce()
The reduce() method processes each Set element and builds an object incrementally.
Example
<!DOCTYPE html>
<html>
<body>
<p id="result2"></p>
<script>
const vehicles = new Set(['RC', 'RX100', 'DUKE', 'VESPA']);
const getObjectFromSet = (set) => {
return [...set].reduce((obj, value) => {
obj[value] = "";
return obj;
}, {});
}
document.getElementById("result2").innerHTML = JSON.stringify(getObjectFromSet(vehicles));
</script>
</body>
</html>
{"RC":"","RX100":"","DUKE":"","VESPA":""}
Method 3: Using Object.fromEntries()
Object.fromEntries() creates an object from key-value pairs. This is the most modern and concise approach.
Example
<!DOCTYPE html>
<html>
<body>
<p id="result3"></p>
<script>
const movies = new Set(['Avatar', 'RRR', 'Bheem', 'Dheera']);
const getObjectFromSet = (set) => {
return Object.fromEntries(Array.from(set, (value) => [value, ""]));
}
document.getElementById("result3").innerHTML = JSON.stringify(getObjectFromSet(movies));
</script>
</body>
</html>
{"Avatar":"","RRR":"","Bheem":"","Dheera":""}
Comparison of Methods
| Method | Readability | Performance | Browser Support |
|---|---|---|---|
Object.assign() |
Medium | Good | ES2015+ |
Array.reduce() |
Good | Good | ES5+ |
Object.fromEntries() |
Best | Best | ES2019+ |
Conclusion
Object.fromEntries() is the most elegant solution for converting Sets to objects in modern JavaScript. For older browser support, Array.reduce() provides a reliable alternative with excellent readability.
