js object new key code example

Example 1: javascript object as key

var fighters = new WeakMap();
var bruce = {name: 'Bruce Lee'};
var chuck = {name: 'Chuck Norris'};

fighters.set(bruce, 'Jeet Kune Do');
fighters.set(chuck, 'Karate');

console.log(fighters.get(bruce)); // Jeet Kune Do
console.log(fighters.get(chuck)); // Karate

Example 2: js create object with keys

var users = [{userId: "1", name: 'harald'}, {userId: "2", name: 'jamie'}];    
var obj = {};
users.forEach(user => {
  obj = {
    ...obj,
    [user.userId]: user,
  }
})
console.log(obj)
// {
//   1: {userId: "1", name: "harald"}
//   2: {userId: "2", name: "jamie"}
// }