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.
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)
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";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With