Create object from array

Simply

 const obj = {};

 for (const key of yourArray) {
      obj[key] = whatever;
 }

or if you prefer “functional” style:

 const obj = yourArray.reduce((o, key) => Object.assign(o, {[key]: whatever}), {});

using the modern object spread operator:

const obj = yourArray.reduce((o, key) => ({ ...o, [key]: whatever}), {})

Example:

[
  { id: 10, color: "red" },
  { id: 20, color: "blue" },
  { id: 30, color: "green" }
].reduce((acc, cur) => ({ ...acc, [cur.color]: cur.id }), {})

Output:

{red: 10, blue: 20, green: 30}

Here is how it works:

reduce is initialized with an empty object (empty {} at the end), therefore first iteration variables are acc = {} cur = { id: 10, color: "red" }. Function returns an object – this is why function body is wrapped in parentheses => ({ ... }). Spread operator doesn’t do anything on the first iteration, so red: 10 is set as first item.

On the second iteration variables are acc = { red: 10 } cur = { id: 20, color: "blue" }. Here the spread operator expands acc and the function returns { red: 10, blue: 20 }.

Third iteration acc = { red: 10, blue: 20 } cur = { id: 30, color: "green" }, so when acc is spread inside the object, our function returns the final value.

Leave a Comment