Search code examples
javascriptruby-on-railsecmascript-6reduxmap-function

How to convert array of model objects to object with model ids as keys?


In Javascript I have an array of model objects:

[  
   {  
      "id":13,
      "title":"Some title 1",
      "time": "friday"
      ...
   },
   {  
      "id":15,
      "title":"Some title 3",
      "time": "Saturday"
      ...
   },
   {  
      "id":16,
      ...
   },
   ...
]

(there is more than 2 values and properties on each object) I want to get an object with each id from the array moved to key, like so:

{
  13: {
    title: "Some title 1",
    time: "Friday"
    ...
  },
  15: {
    title: "Some title 3",
    time: "Saturday"
    ...
  },
  16: {
    ...
  },
  ...
}

I am producing the array with Rails view .to_json include: {} syntax, so an answer in rails would also work for me. I will use the result object with Redux for an initial state so some kind of Redux answer is great too. Also would be interested in both es6 and es5 answer (I will use es5 answer though because Rails doesn't compile es6 in views, but later we are porting to client side application where it would also apply).


Solution

  • The simplest solution is to iterate over the array and attach a copy of each item to a new object:

    let result = {};
    for (let item of data) {
      let newObject = Object.assign({}, item);
      result[newObject.id] = newObject;
      delete newObject.id;
    }
    

    If you don't need the data array later on it gets even simpler:

    let result = {};
    for (let item of data) {
      result[item.id] = item;
      delete item.id;
    }