convert set to object

后端 未结 4 1250
旧时难觅i
旧时难觅i 2021-01-20 20:07

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

相关标签:
4条回答
  • 2021-01-20 20:50

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

    0 讨论(0)
  • 2021-01-20 21:00

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

    0 讨论(0)
  • 2021-01-20 21:03

    Here's one way:

    [...uom].reduce((o, u) => {
      o[u] = '';
      return o;
    }, {})
    
    0 讨论(0)
  • 2021-01-20 21:11

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

    0 讨论(0)
提交回复
热议问题