js add to 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: js push in object

let obj = {};
let objToAdd1 = { prop1: "1", prop2: "2" };
let objToAdd2 = { prop3: "3", prop4: "4" };

// obj variabile could be empty or not, it's the same
obj = { ...obj, ...objToAdd1 };
obj = { ...obj, ...objToAdd2 };

// Note that i used the spread operator... This syntax is available
// only for the most recent js ES (from ES6 on, if i'm not wrong) :)

console.log(obj);

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: Add New Properties to a JavaScript Object

var myDog = {
  "name": "Happy Coder",
  "legs": 4,
  "tails": 1,
  "friends": ["freeCodeCamp Campers"]
};

myDog.bark = "woof";
// or
myDog["bark"] = "woof";

Example 5: javascript append to object

How about storing the alerts as records in an array instead of properties of a single object ?

var alerts = [ 
    {num : 1, app:'helloworld',message:'message'},
    {num : 2, app:'helloagain',message:'another message'} 
]
And then to add one, just use push:

alerts.push({num : 3, app:'helloagain_again',message:'yet another message'});

Example 6: js add data in object

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