Search code examples
javascriptarraysjavascript-objects

How can I convert an Array into a Object?


I have the following array:

['2020-01-16', '2020-01-17', '2020-01-18']

I need to turn the array above into an object like this:

{
    '2020-01-16': {selected: true, marked: true, selectedColor: 'blue'},
    '2020-01-17': {selected: true, marked: true, selectedColor: 'blue'},
    '2020-01-18': {selected: true, marked: true, selectedColor: 'blue'},
}

Is there a way I can do this?


Solution

  • Sure, using Array.reduce(), this is a pretty straightforward thing. The accumulator in the reduce function is simply an empty object, and each iteration through reduce, we create a new property with that array item's value as the property name, and define the object literal as the value of that property.

    Hope this helps!

    const myArray = ['2020-01-16', '2020-01-17', '2020-01-18'];
    
    const myObject = myArray.reduce( (obj, item) => {
      obj[item] = {selected: true, marked: true, selectedColor: 'blue'};
      return obj;
     }, {});
     
     console.log(JSON.stringify(myObject) );