I have a set which needs to be converted into an object with the set\'s unique values as the object keys and an empty string as each element\'s value in the object.
H
You can use Array.prototype.reduce
to get the elements from the set and accumulate it in an object:
const uom = new Set(['inches', 'centimeters', 'yards', 'meters']);
const getObjectFromSet = (set) => {
return [...set].reduce((r, k) => {r[k] = ""; return r; },{});
}
console.log(getObjectFromSet(uom));
You can also use the Object.fromEntries
for ES6+ code:
const uom = new Set(['inches', 'centimeters', 'yards', 'meters']);
const getObjectFromSet = (set) => {
return Object.fromEntries(Array.from(set, (k) => [k, ""]));
}
console.log(getObjectFromSet(uom));