Home > Software engineering >  Javascript: How to convert a Map to an Object that has an object as its keys?
Javascript: How to convert a Map to an Object that has an object as its keys?

Time:04-15

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.

CodePudding user response:

…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.

CodePudding user response:

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)

CodePudding user response:

I don't know if this is the answer to your question. Object.fromEntries() method transforms a list of key-value pairs into an object.

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

const obj = Object.fromEntries(users);

console.log(obj)

  • Related