add objects javascript code example

Example 1: object object javascript

person = {
    'name':'john smith'
    'age':41
};

console.log(person);
//this will return [object Object]
//use
console.log(JSON.stringify(person));
//instead

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