0

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.

4

2 回答 2

0

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"]
于 2015-02-12T11:01:51.733 回答
0
// Fields needs to be an object rather than an array
var Fields = {};

// loop over your fields array
for (var i = 0; i < fields.length; i++){

    // then just assign each field as the key to the Fields object
    Fields[fields[i]] = {
       NewForm: countryFieldTemplate,
       EditForm: continentFieldTemplate
    };
}

DEMO

于 2015-02-12T11:02:47.257 回答