loading...

Convert array to object using reduce()

318097 profile image Mehul Lakhanpal Originally published at codedrops.tech ・1 min read
const list = [
  { label: "javascript", color: "blue" },
  { label: "html", color: "red" },
  { label: "css", color: "green" },
];

const initialValue = {};
const convertToObject = (result, item) => {
  const language = item.label;
  const color = item.color;

  return {
    ...result,
    [language]: color,
  };
};

const palette = list.reduce(convertToObject, initialValue);

console.log(palette); // { javascript: 'blue', html: 'red', css: 'green' }
Enter fullscreen mode Exit fullscreen mode

Thanks for reading πŸ’™

Follow @codedrops.tech for daily posts.

Instagram ● Twitter ● Facebook

Micro-Learning ● Web Development ● Javascript ● MERN stack ● Javascript

codedrops.tech

Discussion

pic
Editor guide
Collapse
ldrmuse profile image
Melissa Heying

Do you mind explaining what’s happening in the reduce? I understand this code up until then. (I’m a newer developer). Thanks 😊

Collapse
maurooquinteros profile image
Mauro Quinteros

Hi Melissa, I'm going to try to explain to you what's happening in that part of the code.

const initialValue = {};

// result is the accumulator that will store all the data in the array.
// its initial value is an empty object that is indicated in the second parameter
// of the reduce function (initialValue variable)
const convertToObject = (result, item) => {
  // item is an object that has label and color properties
  const language = item.label;
  const color = item.color;

  // this returns everything that has the result so far thanks to the spread 
  // operator and adds the new pair.
  return {
    // this's a spread operator
    ...result,
    // here, we assign the new key-value pair
    [language]: color,
  };
};

const palette = list.reduce(convertToObject, initialValue);
Enter fullscreen mode Exit fullscreen mode

I hope you have understood me!

Collapse
ldrmuse profile image
Melissa Heying

Oh I see it! That was very helpful. Thank you for spending the time to explain it!

Thread Thread
maurooquinteros profile image
Mauro Quinteros

You're welcome, I'm also starting in web development. If you have any other questions, let me know.

Thread Thread
318097 profile image
Mehul Lakhanpal Author

Thanks Mauro for the explanation