js object push key value code example

Example 1: js add key to object

// given
const obj = {
    key1: value1,
    key2: value2
};

// add pair
obj["key3"] = value3;
obj.key4 = value4;

Example 2: how to add field to object in js

// original object { key1: "a", key2: "b"}
var obj = {
    key1: "a",
    key2: "b"
};

// adding new filed - you can use 2 ways
obj.key3 = "c"; // static
// or
obj["key3"] = "c"; // dynamic - 'key3' can be a variable
console.log(obj) // {key1: "a", key2: "b", key3: "c" }

Example 3: javascript add to object

var element = {}, cart = [];
element.id = id;
element.quantity = quantity;
cart.push(element);

// Array of Objects in form {element: {id: 10, quantity: 10} }
var element = {}, cart = [];
element.id = id;
element.quantity = quantity;
cart.push({element: element});

Example 4: javascript push object into array with variable key

//Normal Javascript
var key = "happyCount";
var obj = {};
obj[key] = someValueArray;
myArray.push(obj);

//OR

//If you're able to use ES6 and Babel, you can use this new feature:

{
    [yourKeyVariable]: someValueArray,
}

Example 5: js add data in object

var element = {}, cart = [];
element.id = id;
element.quantity = quantity;
cart.push(element);