add elements to an object javascript code example

Example 1: append object to object javascript

// Spread syntax allows an iterable (in this case an object) to be expanded

const originalObj = { name: 'John', age: 34 }
let newObj = { ...originalObj, city: 'New York' }
// newObj is now { name: 'John', age: 34, city: 'New York' }

// it can also be used with the same object
newObj = { ...newObj, language: 'en' }
// { name: 'John', age: 34, city: 'New York', language: 'en' }

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