DEV Community

Mehul Lakhanpal
Mehul Lakhanpal

Posted on Originally published at codedrops.tech

Convert array to object using reduce()

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

Top comments (3)

Collapse
 
mauroquinteroos 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!

 
mauroquinteroos 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
 
ml318097 profile image
Mehul Lakhanpal •

Thanks Mauro for the explanation