Search code examples
javascripttemplatesfacebook-messenger-bot

JavaScript - How to dynamically add to a nested object array


I am trying to make a messenger bot that can create buttons based on a number I enter. The code looks like this:

let messageData = {
    "attachment": {
        "type": "template",
        "payload": {
            "template_type": "button",
            "text": text[1],
            "buttons":[]
        }
    }
}

The part that says "buttons":[] is where I want to add buttons (inside the []) according to this format:

{
   "type":"postback",
   "title":"button" + i //where i is the button number,
   "payload":"button" + i
}

How would I go about doing this?


Solution

  • For your example you can do this:

    messageData.attachment.payload.buttons.push(obj) 
    

    the . accesses the object's key, which can also be done this way messageData['attachment'] The difference between

    messageData.attachment
    

    and

    messageData['attachment']
    

    is that the second one can take a variable instead of a string, e.g.

    var use_key = 'attachment';
    messageData[use_key];
    

    will access the same as the other two above.

    JSON is just short for JavaScript Object Notation. And you make it exactly like your second example:

    {
       "type":"postback",
       "title":"button" + i //where i is the button number,
       "payload":"button" + i
    }
    

    You can assign it to a variable to pass it into the push, or just exactly as it is. Not much different from a string or number. Don't let all the extra information scare you.