Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

181
Views
javascript: create dictionary from array of key-values objects

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 => (???) }
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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);

about 4 years ago · Juan Pablo Isaza Report

0

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);

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!