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

264
Views
Javascript: How to convert a Map to an Object that has an object as its keys?

let johnB = { name: "John Boy" },
    lilyA = { name: "Lily Allen" },
    peterD = { name: "Peter Drucker" };
    
const users = new Map([
  [johnB, 'boudler'], 
  [lilyA, 'rock'],
  [peterD, 'stone']
])

const obj = {};
users.forEach((value, key) => obj[key].name = value)

console.log(obj)

The above doesn't work but it shows the basic intent. I want to get name property from the map keys to be the key when the Map is "converted" to an object. Accessing just the key(without .name), javascript stringifies the object so you end up with [object, Object] as the key.

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

0

…an Object that has an object as its keys?

That does not exist. An object property cannot have an object as the key, it must be a string or a symbol. What are you attempting to achieve is simply not possible. Keep using the Map - that's what it is meant to be used for.

about 4 years ago · Juan Pablo Isaza Report

0

I think you just have your logic wrong in your foreach loop.. Is this what you were expecting?

{
  "John Boy": "boudler",
  "Lily Allen": "rock",
  "Peter Drucker": "stone"
}

let johnB = { name: "John Boy" },
    lilyA = { name: "Lily Allen" },
    peterD = { name: "Peter Drucker" };
    
const users = new Map([
  [johnB, 'boudler'], 
  [lilyA, 'rock'],
  [peterD, 'stone']
])

const obj = {};
users.forEach((value, key) => obj[key.name] = value)

console.log(obj)

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!