1

I'm trying to create a navigational menu out of some data. In order to do this I need to manipulate the data into an object of arrays. I am attempting to do this using map(), I've gotten to the point of making the keys of the object and a corresponding value, however, I don't know how to handle the multiple titles under it's corresponding year. Any help would be greatly appreciated.

const data = [
   {
     "fields": {
       "title": "Frozen Thorns",
       "year": 2017,
     }
   },
   {
     "fields": {
       "title": "The Professional Years",
       "year": 2018,
     }
   },
   {
     "fields": {
       "title": "Green Nothing",
       "year": 2018,
     }
   },
   {
     "fields": {
       "title": "The Next Voyage",
       "year": 2018,
     }
   },
   {
     "fields": {
       "title": "Smooth Sorcerer",
       "year": 2019,
     }
   },
   {
     "fields": {
       "title": "Azure Star",
       "year": 2019,
     }
   }]

   const menu = Object.assign({}, ...data.map(item => ({[item.fields.year]: item.fields.title})));
   
   
   // OUTPUT 
   
   // {
   //    2017: "Frozen Thorns",
   //    2018: "The Next Voyage",
   //    2019: "Azure Star"
   // }
   
   // DESIRED OUTPUT

   // {
   //    2017: ["Frozen Thorns"],
   //    2018: ["The Professional Years", "Green Nothing", "The Next Voyage"],
   //    2019: ["Smooth Sorcerer", "Azure Star"]
   // }
   
CalAlt
  • 1,683
  • 2
  • 15
  • 29

1 Answers1

1

The general rule is that if you want to keep the same shape as your original array, then you use map, but if you want to turn it into a smaller shape you use the appropriately named reduce. Take a look at this.

const data = [
   {
     "fields": {
       "title": "Frozen Thorns",
       "year": 2017,
     }
   },
   {
     "fields": {
       "title": "The Professional Years",
       "year": 2018,
     }
   },
   {
     "fields": {
       "title": "Green Nothing",
       "year": 2018,
     }
   },
   {
     "fields": {
       "title": "The Next Voyage",
       "year": 2018,
     }
   },
   {
     "fields": {
       "title": "Smooth Sorcerer",
       "year": 2019,
     }
   },
   {
     "fields": {
       "title": "Azure Star",
       "year": 2019,
     }
   }];

   const menu = data.reduce((accumulator, currentValue) => { 
     accumulator[currentValue.fields.year] = (accumulator[currentValue.fields.year] || []).concat(currentValue.fields.title);
     return accumulator;
   }, {});
   
console.log(menu);
Todd Chaffee
  • 6,754
  • 32
  • 41