knot22
knot22

Reputation: 2768

convert set to object

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?

Upvotes: 8

Views: 7183

Answers (5)

Joeboulton
Joeboulton

Reputation: 320

For anyone like myself who was looking for the reverse of this for something similar to the below

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

This code worked for me

        const mySet = new Set(['inches', 'centimeters', 'yards', 'meters']);
        let newArr = [];

        const setToObj = [...mySet].map(el => {
          newArr.push({ 'length': el });
        });

Upvotes: 0

Nick Parsons
Nick Parsons

Reputation: 50639

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

Upvotes: 8

Fullstack Guy
Fullstack Guy

Reputation: 16908

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

Upvotes: 0

Brett Zamir
Brett Zamir

Reputation: 14345

Here's one way:

[...uom].reduce((o, u) => {
  o[u] = '';
  return o;
}, {})

Upvotes: 1

Quentin
Quentin

Reputation: 943100

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

Upvotes: 2

Related Questions