Mathias Osterhagen
Mathias Osterhagen

Reputation: 424

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.

Upvotes: 0

Views: 57

Answers (3)

Yves Kipondo
Yves Kipondo

Reputation: 5623

You can use Array.prototype.reduce method to convert an array to another type

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

let output = arr.reduce((accumulator, current) => {
  return {...accumulator, [current]: null}
}, {})

console.log(output);

Upvotes: 1

daniloxxv
daniloxxv

Reputation: 865

reduce could turn it into a one-liner:

var obj = arr.reduce((acc, curr)=> ({...acc, [curr]: null}),{})

Upvotes: 2

pbialy
pbialy

Reputation: 1083

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.

Upvotes: 2

Related Questions