Kern Elliott Kern Elliott - 26 days ago 7
JSON Question

Insert New Entries into last JSON item

I have a JSON structure that looks like this

{
"messages":[
{
text: 'Some text'
},
{
text: 'Some text again'
},
{
text: 'Some text again again'
}
]
}


I will like to insert a new object into the last
text
object so that the structure now looks like this

"messages":[
{
text: 'Some text'
},
{
text: 'Some text again'
},
{
text: 'Some text again again',
"quick_replies": [
{
"title":"Loved it!",
"block_names": ["Block 1"]
},
{
"title":"test",
"block_names": ["Block 1"]
}
]
}
]
}


I was trying to use
message[0].text.text.text = quick_replies...
however I don't think that solution will work as the
,
would be missing and would cause an error.

How can I insert the new data into the JSON structure?

Answer Source

If you want to access the last message, use length - 1:

myObj.messages[myObj.messages.length - 1].quick_replies = [
        {
            "title":"Loved it!",
            "block_names": ["Block 1"]
        },
        {
            "title":"test",
            "block_names": ["Block 1"]
        }
    ];