javascriptarrayspushjslink

Push in my javascript array


I need some help for my JSlink code.

I used this code, it work well:

var Fields = {
    "Continent": {
            "NewForm": FieldTemplate,
            "EditForm": FieldTemplate
    },
    "Country": {
            "NewForm": FieldTemplate,
            "EditForm": FieldTemplate
    },
    "City": {
            "NewForm": FieldTemplate,
            "EditForm": FieldTemplate
    }
};

But I would like to make it dynamic so I tried this:

for (var i = 0; i < fields.length; i++){
    Fields.push(fields[i].name: {
        "NewForm": countryFieldTemplate,
         "EditForm": continentFieldTemplate
    });
}

In the for loop, fields is an array who contains "Continent", "Country" and "City" but my code don't work and I want to know why. Thanks in advance.


Solution

  • You can create properties on a JavaScript object using the syntax:

    Object[propertyName] = propertyValue;
    

    So this should work:

    var Fields = {};
    for (var i = 0; i < fields.length; i++){
        Fields[fields[i]] = {
            "NewForm": countryFieldTemplate,
             "EditForm": continentFieldTemplate
        };
    }
    

    Where fields is:

    var fields = ["Continent", "Country", "City"]