0

I am trying to create sample data to test a form Grid. And am using the following function to try and create the data to send to my grid.

// populateFields: Populates data n times a record of data for the SSM form.
// @params: n, fips, products
// @returns: fields
populateFields(n, fips, products) {
    var data = [];
    var fields = this.getFields();


    for(i = 0; i < n; i++) {
        var x = {fields[0]: false, 
        fields[1]: fips[getRandomInt(0, fips.length())], 
        fields[2]: products[getRandomInt(0, products.length())], 
        fields[3]: getRandomInt(0, 100)};
        data.push(x);
    }

    return data;
}

Nothing gets populated when I call it. I get an error saying fields[0]: false needs [ token.

Note: This is part of a class, I don't think that matters. I am not sure if you want to see how I call it.

Is it because of jQuery, as in what I am passing the array to.

2
  • One other minor issue: you don't declare your loop counter, i. Commented Aug 20, 2018 at 20:17
  • 1
    One question, though: does getFields() return varying results? If so, how do you know that fields[1] has anything to do with "fips" or that fields[2] is related to "products"? Commented Aug 20, 2018 at 20:18

1 Answer 1

5

To use a variable as a property key it has to be enclosed in brackets:

 {
   [fields[0]]: false
   //...
 }

Otherwise it would try to use field[0] as an identifier itself, and some characters like [ arent allowed in identifiers (cause they are used for property access). (They are allowed in property names though, so { "field[0]": false } would work syntactically, but that makes little sense).

Sign up to request clarification or add additional context in comments.

3 Comments

@raxenx glad to help :)
The commentary is slightly misleading. The new(ish) bracket syntax for Object keys allows us to do in a single step what previously took multiple steps. (myObj = { ... }; myObj[fieldName] = value; ...), but it doesn't change what is an allowable property name, Symbols and any Strings. So this is a perfectly acceptable property name: "(ab [no I ^meant cd])!" even though its full of spaces and special characters. Of course that isn't a legal identifier name, but that's a slightly different question than one about object property names.
@scott yup but without the [] or "" its an identifier.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.