how to add item to object javascript 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: adding element to javascript object

let person = {
  name : 'John Doe',
  age : 35
}

//Now we can add element by 2 ways
person.occupation = 'Web Designer'
//or
person['occupation'] = 'Web Designer'; //This is usefull for adding element within loop.

object[yourKey] = yourValue;
object.yourKey = yourValue;

Example 3: how to add items to object in javascript

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});