Skip to content Skip to sidebar Skip to footer

Can You Populate An Object's Keys Directly From An Array In Javascript?

Is it possible to directly populate an object's keys from an array in JavaScript? Something like var a = ['a', 'b', 'c']; var b = {} b[a] = [1, 2, 3]; // {a:1, b:2, c:3} In othe

Solution 1:

If you have a known number of properties, that can be done using destructuring:

const b = {};
 ([b.a, b.b, b.c] = [1, 2, 3]);

Otherwise you have to build key-value pairs, and turn them into an object:

const keys = ["a", "b", "c"];
 const values = [1, 2, 3];

 const result = Object.fromEntries(keys.map((key, i) => [key, values[i]]));

Unfortunately there is no native Array.zip that would simplify this but some libraries do support that:

const result = Object.fromEntries(_.zip(keys, values));

I think thats quite nice.


And no, b[a] = will always set the a property of b, otherwise that would be really confusing.

Solution 2:

try

a.reduce( (o,c,i)=>({...o,[c]:i}), {})

var a = ["a", "b", "c"];

var b= a.reduce( (o,c,i)=>({...o,[c]:i}), {})

console.log(b);

Post a Comment for "Can You Populate An Object's Keys Directly From An Array In Javascript?"