views:

3537

answers:

5
+3  Q: 

Append to json

Hey everyone,

I have a json object that hold alerts and information about them:

var alerts = { 1:{app:'helloworld','message'},2:{app:'helloagain',message:'another message'} }

along with 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 json object?

+13  A: 

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

var alerts = [ 
    {num : 1, app:'helloworld','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'});
Andreas Grech
A: 

Do you have the ability to change the outer-most structure to an array? So it would look like this

var alerts = [{"app":"helloworld","message":null},{"app":"helloagain","message":"another message"}];

So when you needed to add one, you can just push it onto the array

alerts.push( {"app":"goodbyeworld","message":"cya"} );

Then you have a built-in zero-based index for how the errors are enumerated.

Peter Bailey
+1  A: 

You should really go with the array of alerts suggestions, but otherwise adding to the object you mentioned would look like this:

alerts[3]={"app":"goodbyeworld","message":"cya"};

But since you shouldn't use literal numbers as names quote everything and go with

alerts['3']={"app":"goodbyeworld","message":"cya"};

or you can make it an array of objects.

Accessing it looks like

alerts['1'].app
=> "helloworld"
dlamblin
A: 

Try this:

alerts.splice(0,0,{"app":"goodbyeworld","message":"cya"});

Works pretty well, it'll add it to the start of the array.

HM2K
A: 

jQuery $.extend(obj1, obj2) would do this for you.

var alerts = { 1:{app:'helloworld','message'},2:{app:'helloagain',message:'another message'} }

$.extends(alerts, {app:'new',message:'message'});

Kevin