Appending to an object

后端 未结 13 1312
心在旅途
心在旅途 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 10:55

    Try this:

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

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

    0 讨论(0)
  • 2020-11-27 10:56

    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

    0 讨论(0)
  • 2020-11-27 10:58

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

    0 讨论(0)
  • 2020-11-27 11:00

    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" ]
    
    0 讨论(0)
  • 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();
    }

    0 讨论(0)
  • 2020-11-27 11:03

    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}
    }
    
    0 讨论(0)
提交回复
热议问题