how to create object with certain key javascript code example

Example 1: javascript create object key from variable

//For ES6 and Babel
{
    [yourKeyVariable]: "yourValue",
}

// ES5 Alternative
// Create the object first, then use [] to set your variable as a key
var yourObject = {};

yourObject[yourKeyVariable] = "yourValue";

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"}
// }