user3776662 user3776662 - 5 months ago 15
JSON Question

how to set a JSON object equal to another JSON object within the parent's declaration

I'm new to javascript and json and messing around with some code.

This is the format of my JSON object

messageData = {
"attachment": {
"type": "template",
"payload": {
"template_type": "generic",
elements: [{
title: "titleOne",
subtitle: "subtitleOne"
}, {
title: "titleTwo",
subtitle: "subtitleTwo"
}]
}
}
}


Instead of going in an individually adding each title and subtitle object to elements I want to do this with a loop and just set one object equal to an array that contains many more numbers of title and subtitle objects. So lets say I have the object titles:

titles = {} //100 objects with different titles and subtitles.


Is there a way to implement this logic shown below?

messageData = {
"attachment": {
"type": "template",
"payload": {
"template_type": "generic",
elements = titles
}
}
}


Correctly formatting everything? Thanks for the help!

Answer

You have a variable titles which has an array of objects assigned to it. Something like:

var titles = [{...}, {...}, ...];

You later want to assign this array (currently assigned to the variable titles) to a property of an object (in this case elements):

var messageData = {
    attachment: {
        type: "template",
        payload: {
            template_type: "generic", 
            elements // <-- here
        } 
    }
}

(Please note that I removed double quotes from the property names, they are not necessary as they have a valid notation)

As you suspected, nothing is easier than this:

var messageData = {
    attachment: {
        type: "template",
        payload: {
            template_type: "generic", 
            elements: titles
        } 
    }
}

This would be enough as an answer, but let's take a small step back now: in javascript pretty much everything is an object (I'm simplifying a little bit here, strings are not objects for example, but I invite you to find out more by yourself). But yes, as confusing as it sounds at first, an array is an object.

Another thing to know is that in javascript objects are assigned by reference. This means that if you modify the original titles array, the elements array would be modified as well. They are just two names pointing at the very same object.

In your particular case this detail might not matter, but if you want to separate the lives of titles and elements you need to clone the original array, before you assign it again. And the fastest way is passing through a JSON conversion:

var titles_0 = JSON.parse(JSON.stringify(titles));
var messageData = {
    attachment: {
        type: "template",
        payload: {
            template_type: "generic", 
            elements: titles_0
        } 
    }
}