DEV Community


Discussion on: Convert array to object using reduce()

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
    // 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!

codetivated 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