add item to javascript object code example

Example 1: 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 2: ad data to js object

//Consider the following example object literal:
var myObject = {
    sProp: 'some string value',
    numProp: 2,
    bProp: false
};

//You can use dot syntax to add a new property to it as follows:
myObject.prop2 = 'data here';

//Modify a Property of an Object Literal
//The process for modifying a property is essentially the same. 
//Here we will assign a new value to the sProp property shown in the 
//original myObject definition above:
myObject.sProp = 'A new string value for our original string property';

//Read Current Value of Object Property
//The following demonstrates how to access a property of an object literal:
alert(myObject.sProp) // display myObject.sProp value in alert
var val = myObject.sProp; // assign myObject.sProp to variable

Example 3: js add data in object

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