Appending to an object

后端 未结 13 1497
心在旅途
心在旅途 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:00

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

提交回复
热议问题