-2

I have an array of objects.

const ar = [ {0 : "A"}, {1 : "B"}];

I want to create an dictionary from it

const di =  {0 : "A", 1 : "B"};

I am a little struggling with this conversion. How it is possible to do it using map or reduce?

const di = ar.map( ob => (???) }
K.I.
  • 759
  • 1
  • 11
  • 30

2 Answers2

2

You should use reduce here instead of map. map will give you an array of objects but what you need is an object will all keys. So reduce is the best tool for it.

Main difference between map and reduce

const ar = [{ 0: "A" }, { 1: "B" }];
const di = { 0: "A", 1: "B" };

const result = ar.reduce((acc, curr) => {
  Object.keys(curr).forEach((k) => (acc[k] = curr[k]));
  return acc;
}, {});

console.log(result);
DecPK
  • 24,537
  • 6
  • 26
  • 42
2

A simple reduce can be used to merge all objects. Be aware that the keys need to be unique otherwise you will overwrite them.

The merging is done with the spread syntax

const ar = [{0 : "A"}, {1 : "B"}];

const di = ar.reduce((acc, obj) => ({...acc, ...obj}));

console.log(di);

Another simple approach is the use of Object.assign

const ar = [{0 : "A"}, {1 : "B"}];

const di = Object.assign({}, ...ar);

console.log(di);
Reyno
  • 6,119
  • 18
  • 27