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

122
Views
.map equivalent of .forEach to create an object

The following code populates an object called result with the values in keys as the keys and an empty string as each key's value. This is working as desired.

const keys = ['one', 'two', 'three'];
const result = {};
keys.forEach(key => {
  result[key] = '';
});
console.log(result);

enter image description here

However, I'm wondering if the result object can be created in a single command by using .map. Below is what I've tried but it yields an array of objects rather than a single object.

const result = keys.map(key => ({
  [key]: ''
}));
console.log(result);

enter image description here

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

You can combine Object.fromEntries and map methods. With map you can get array of [key, value] pairs and then by calling fromEntries you get an object from that array.

const keys = ['one', 'two', 'three'];
const result = Object.fromEntries(keys.map(k => ([k, ''])))
console.log(result)

about 4 years ago · Juan Pablo Isaza Report

0

Here's an alternative approach that only needs one method. (Array.prototype.reduce())

const keys = ["one", "two", "three"];

const result = keys.reduce((a, c) => ({ ...a, [c]: "" }), {});
console.log(result);

about 4 years ago · Juan Pablo Isaza Report

0

you can use your map, then reduce:

keys
  .map(k => ({[k]: ""}))
  .reduce((x, r) => ({...x, ...r}), {})
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!