javascriptjsonfacebook-send-api

set json property depending on child property


I am creating this JSON object

 {
    "attachment": {
        "type": "template",
        "payload": {
            "template_type": "generic",
            "image_aspect_ratio": "square"
            "elements": [
                new CreateBallon(results[rand])
            ]
        }
    }
}

I want to set the image_aspect_ratio in only if elements[0].someProp is present. How can I do that?


Solution

  • Let's clear what JSON is. It is a textual notation for data. If you do anything with the object that involves code of Javascript don't call it JSON so, The object you're talking about is not a JSON but a JavaScript object created via object literal notation.

    Now to answer your query, you can't refer to this object before you've fully initialized that object. So what you can do is initialize your object with some default value and then you should be able to edit any property based on the properties from the same object. Something like

     var obj = {"property1" : "X", "property2" : ""};
    

    Now you can update your object like

      obj.property2 = obj.property1 =='yourCondition' ? 'NewValue' : obj.property2