Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

declaring javascript array with multiple fields

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.

like image 786
user1782677 Avatar asked Dec 21 '22 08:12

user1782677


2 Answers

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)
like image 187
Arun P Johny Avatar answered Dec 29 '22 00:12

Arun P Johny


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";
like image 20
Explosion Pills Avatar answered Dec 29 '22 00:12

Explosion Pills