Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert set to object

Tags:

javascript

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.

Here is the set I'm working with:

const uom = new Set(['inches', 'centimeters', 'yards', 'meters']);

I've tried this:

const uomObj = {...[...uom]};
console.log(uomObj);

Which yields this:

Object {
  "0": "inches",
  "1": "centimeters",
  "2": "yards",
  "3": "meters",
}

but that does not match the desired result of:

Object {
  "inches": "",
  "centimeters": "",
  "yards": "",
  "meters": "",
}

Can this be achieved with an ES6 approach? If so, how?

like image 630
knot22 Avatar asked Aug 11 '20 12:08

knot22


People also ask

How do you convert a set to an object?

Create an object, then loop over the values in the set and create a property for each one. The reduce method is probably the most compact way to do that. Show activity on this post. Show activity on this post.

What is set object in JavaScript?

The Set object lets you store unique values of any type, whether primitive values or object references.

Does JavaScript set work with objects?

Sets are supposed to contain unique objects, but it doesn't work for objects in javascript.


Video Answer


3 Answers

You can use Array.from with a mapping function to convert each value inside your set into an object and then use Object.assign() with the spread syntax to merge the array of objects into a single resulting object like so:

const uom = new Set(['inches', 'centimeters', 'yards', 'meters']);
const res = Object.assign(...Array.from(uom, v => ({[v]:''})));
console.log(res);
like image 176
Nick Parsons Avatar answered Oct 07 '22 02:10

Nick Parsons


Here's one way:

[...uom].reduce((o, u) => {
  o[u] = '';
  return o;
}, {})
like image 24
Brett Zamir Avatar answered Oct 07 '22 02:10

Brett Zamir


Create an object, then loop over the values in the set and create a property for each one. The reduce method is probably the most compact way to do that.

const uom = new Set(['inches', 'centimeters', 'yards', 'meters']);
const result = Array.from(uom).reduce( (a,c) => { a[c]=""; return a; }, {});
console.log(result);
like image 1
Quentin Avatar answered Oct 07 '22 04:10

Quentin