0

I have array of objects:

const objects = [
  {id: 2, name: "aaa"},
  {id: 4, name: "bbb"},
  {id: 11, name: "ccc"},
  {id: 21, name: "ddd"}
];

Is any option to do new object based on ids from objects?

I would like to receive:

const list = {
   2: false,
   4: false,
   11: false,
   21: false
};

I can iterate through objects but maybe exists better way?

tolu
  • 59
  • 1
  • 1
  • 5
  • 1
    Why does everyone tend to avoid loops? What is wrong with iteration? For manipulating/accessing/... arrays of elements you **always** need to _iterate_! – Ram Sep 17 '18 at 20:15
  • What exactly are you doing? Where did the `14: false` come from? Where did `21` go? – CodeDraken Sep 17 '18 at 20:17
  • @CodeDraken sorry, it was my mistake – tolu Sep 17 '18 at 20:22

1 Answers1

1

I like to use array.reduce for this. Reduce takes an array and "reduces" it to some other value.

var byId = objects.reduce(function(map, obj){
  map[obj.id] = obj;
  return map;
}, {})
aclave1
  • 1,680
  • 18
  • 29
  • Thanks. And do you know what efficiency it has compared to a regular loop? – tolu Sep 17 '18 at 20:31
  • 1
    array.reduce is usually implemented with native code(c++) which I'd guess would be faster than even a jit-ted javascript for-loop. I would not worry about the performance of the loop construct itself but rather what you're doing inside of it. – aclave1 Sep 17 '18 at 20:35