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?
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'});
This answer expects you to know the id of the alert to be added. Well, if you already know that, then you can simply follow the original object format and do:
alerts[3] = { app: 'hello3', message: 'message 3' }
. With this you can access a message by id:alerts[2] => { app: 'helloworld', message: 'message' }
. Getting the length is then just:Object.keys(alerts).length
(that bit is easier with arrays)