Appending to an object

后端 未结 13 1553
心在旅途
心在旅途 2020-11-27 10:19

I have an object that holds alerts and some information about them:

var alerts = { 
    1: { app: \'helloworld\', message: \'message\' },
    2: { app: \'hel         


        
13条回答
  •  甜味超标
    2020-11-27 11:15

    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!!

提交回复
热议问题