javascript create object with keys and values code example
Example 1: javascript create object key from variable
{
[yourKeyVariable]: "yourValue",
}
var yourObject = {};
yourObject[yourKeyVariable] = "yourValue";
Example 2: javascript add to object
var element = {}, cart = [];
element.id = id;
element.quantity = quantity;
cart.push(element);
var element = {}, cart = [];
element.id = id;
element.quantity = quantity;
cart.push({element: element});
Example 3: 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)