I have an object that holds alerts and some information about them:
var alerts = { 1: { app: 'helloworld', message: 'message' }, 2: { app: 'helloagain', message: 'another message' } }
In addition to this, I have a variable that says how many alerts there are, alertNo
. My question is, when I go to add a new alert, is there a way to append the alert onto the alerts
object?
To add items and objects to an array, you can use the push() function in JavaScript. The push() function adds an item or object at the end of an array. For example, let's create an array with three values and add an item at the end of the array using the push() function.
The easiest way to merge two objects in JavaScript is with the ES6 spread syntax / operator ( ... ). All you have to do is insert one object into another object along with the spread syntax and any object you use the spread syntax on will be merged into the parent 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'});
jQuery $.extend(obj1, obj2)
would merge 2 objects for you, but you should really be using an array.
var alertsObj = { 1: {app:'helloworld','message'}, 2: {app:'helloagain',message:'another message'} }; var alertArr = [ {app:'helloworld','message'}, {app:'helloagain',message:'another message'} ]; var newAlert = {app:'new',message:'message'}; $.extend(alertsObj, newAlert); alertArr.push(newAlert);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With