Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Appending to an object

Tags:

javascript

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?

like image 230
Steve Gattuso Avatar asked Mar 05 '09 22:03

Steve Gattuso


People also ask

Can you add an array to an 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.

How do you join two objects in JavaScript?

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.


2 Answers

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'}); 
like image 103
Andreas Grech Avatar answered Oct 12 '22 22:10

Andreas Grech


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); 
like image 33
respectTheCode Avatar answered Oct 12 '22 23:10

respectTheCode