Search code examples
javascriptarraysjsonshortest

Array value to properties name javascript


Is there a one-line way to transform array value to the properties name of an object?

Example:

var arr = ['name', 'age', 'size'];

To

{'name' :null, 'age':null, 'size':null}

Actually I'm processing like this:

var arr = ['name', 'age', 'size'];
let obj = {};
arr.map(z => obj[z] = null);

I suppose that is the shortest way but I'm not sure.


Solution

  • Use reduce:

    arr.reduce((prev, curr) => {
      return Object.assign(prev, {[curr]: null})
    }, {})
    

    or you can one-line it if you want, but imo it looks worse then:

    arr.reduce((prev, curr) => Object.assign(prev, {[curr]: null}), {})
    

    Note, that Object.assign is a better way to code this, rather than using spread operator ({... }).

    Spread operator creates a NEW object every loop. This can lead to big performance issues.

    Object.assign on the other hand works on the first object.