3

So I want to declare a javascript array with multiple fields.

For example I know you can do something like

var data = [
{
    "field one": "a",
    "field two": "b",
},
{  
    "field one": "c",
    "field two": "d",
}
]

However, I don't know to do create such an array dynamically so that I don't have to initialize the fields at declaration time.

3 Answers 3

6

You can add values dynamically to an array using the push() method.

var data  = [];
....
....
data.push({
    "field one": "a",
    "field two": "b",
})

Also if you want to add keys to an existing object dynamically, you can use the [] syntax

var obj = {};
...
obj['field one'] = 'a';
obj['field two'] = 'b';
data.push(obj)
Sign up to request clarification or add additional context in comments.

Comments

2

Each individual array element is a JavaScript Object. You can create new fields using dot or bracket syntax:

var obj = {};
obj.fieldone = "one";
obj["field two"] = "two";

In your case you have to use bracket notation because of the space.

You can insert newly created objects into the array using .push:

data.push(obj);

You can then access individual fields:

data[0]["field one"] == "a";

Comments

0

Try this:

var data = [];

var fields = ["one", "two"];
var length = fields.length;

var char = 97; // a

for (var i = 0; i < 2; i++) {
    var object = {};

    for (var j = 0; j < length; j++) {
        object["field " + fields[j]] = String.fromCharCode(char++);
    }

    data.push(object);
}

See the demo here: http://jsfiddle.net/yqg3D/

Comments

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.