Appending to an object

Javascript

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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'});

Solution 2 - Javascript

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);

Solution 3 - Javascript

You can do this with Object.assign(). Sometimes you need an array, but when working with functions that expect a single JSON object -- such as an OData call -- I've found this method simpler than creating an array only to unpack it.

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

alerts = Object.assign({3: {app:'helloagain_again',message:'yet another message'}}, alerts)

//Result:
console.log(alerts)
{ 
    1: {app:'helloworld',message:'message'},
    2: {app:'helloagain',message:'another message'}
    3: {app: "helloagain_again",message: "yet another message"}
} 

EDIT: To address the comment regarding getting the next key, you can get an array of the keys with the Object.keys() function -- see Vadi's answer for an example of incrementing the key. Similarly, you can get all the values with Object.values() and key-values pairs with Object.entries().

var alerts = { 
    1: {app:'helloworld',message:'message'},
    2: {app:'helloagain',message:'another message'}
}
console.log(Object.keys(alerts))
// Output
Array [ "1", "2" ]

Solution 4 - Javascript

You can use spread syntax as follows..

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

alerts = {...alerts, 3: {app: 'hey there', message: 'another message'} }

Solution 5 - Javascript

Now with ES6 we have a very powerful spread operator (...Object) which can make this job very easy. It can be done as follows:

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

//now suppose you want to add another key called alertNo. with value 2 in the alerts object. 
 
alerts = {
   ...alerts,
   alertNo: 2
 }

Thats it. It will add the key you want. Hope this helps!!

Solution 6 - Javascript

Like other answers pointed out, you might find it easier to work with an array.

If not:

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

// Get the current size of the object
size = Object.keys(alerts).length

//add a new alert 
alerts[size + 1] = {app:'Your new app', message:'your new message'}

//Result:
console.log(alerts)
{ 
    1: {app:'helloworld',message:'message'},
    2: {app:'helloagain',message:'another message'}
    3: {app: "Another hello",message: "Another message"}
}      

try it:

https://jsbin.com/yogimo/edit?js,console

Solution 7 - Javascript

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"

Solution 8 - Javascript

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.

Solution 9 - Javascript

Way easier with ES6:

let exampleObj = {
  arg1: {
    subArg1: 1,
    subArg2: 2,
  },
  arg2: {
    subArg1: 1,
    subArg2: 2,
  }
};

exampleObj.arg3 = {
  subArg1: 1,
  subArg2: 2,
};

console.log(exampleObj);

{
arg1: {subArg1: 1, subArg2: 2}
arg2: {subArg1: 1, subArg2: 2}
arg3: {subArg1: 1, subArg2: 2}
}

Solution 10 - Javascript

As an alternative, in ES6, spread syntax might be used. ${Object.keys(alerts).length + 1} returns next id for alert.

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

alerts = {
  ...alerts, 
  [`${Object.keys(alerts).length + 1}`]: 
  { 
    app: `helloagain${Object.keys(alerts).length + 1}`,message: 'next message' 
  } 
};

console.log(alerts);

Solution 11 - Javascript

I'm sorry but i can't comment your answers already due my reputation!...so, if you wanna modify the structure of your object, you must do like Thane Plummer says, but a little trick if you do not care where to put the item: it will be inserted on first position if you don't specify the number for the insertion.

This is wonderful if you want to pass a Json object for instance to a mongoDB function call and insert a new key inside the conditions you receive. In this case I gonna insert a item myUid with some info from a variable inside my code:

// From backend or anywhere
let myUid = { _id: 'userid128344'};
// ..
// ..

  let myrequest = { _id: '5d8c94a9f629620ea54ccaea'};
  const answer = findWithUid( myrequest).exec();

// ..
// ..

function findWithUid( conditions) {
  const cond_uid = Object.assign({uid: myUid}, conditions);
  // the object cond_uid now is:
  // {uid: 'userid128344', _id: '5d8c94a9f629620ea54ccaea'}
  // so you can pass the new object Json completly with the new key
  return myModel.find(cond_uid).exec();
}

Solution 12 - Javascript

[Javascript] After a bit of jiggery pokery, this worked for me:

 let dateEvents = (
            {
                'Count': 2,
                'Items': [
                    {
                        'LastPostedDateTime': {
                            "S": "10/16/2019 11:04:59"
                        }
                    },
                    {
                        'LastPostedDateTime': {
                            "S": "10/30/2019 21:41:39"
                        }
                    }
                ],
            }
        );
        console.log('dateEvents', dateEvents);

The problem I needed to solve was that I might have any number of events and they would all have the same name: LastPostedDateTime all that is different is the date and time.

Solution 13 - Javascript

Try this:

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

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSteve GattusoView Question on Stackoverflow
Solution 1 - JavascriptAndreas GrechView Answer on Stackoverflow
Solution 2 - JavascriptrespectTheCodeView Answer on Stackoverflow
Solution 3 - JavascriptThane PlummerView Answer on Stackoverflow
Solution 4 - JavascriptinzoView Answer on Stackoverflow
Solution 5 - JavascriptHarshit AgarwalView Answer on Stackoverflow
Solution 6 - JavascriptM.CView Answer on Stackoverflow
Solution 7 - JavascriptdlamblinView Answer on Stackoverflow
Solution 8 - JavascriptPeter BaileyView Answer on Stackoverflow
Solution 9 - JavascriptMaroun MelhemView Answer on Stackoverflow
Solution 10 - JavascriptVadiView Answer on Stackoverflow
Solution 11 - JavascriptMarcView Answer on Stackoverflow
Solution 12 - JavascriptDavid WhiteView Answer on Stackoverflow
Solution 13 - JavascriptHM2KView Answer on Stackoverflow