Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

265
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda