Ivan Hristev
Ivan Hristev

Reputation: 51

JS fill Object as an array

can you tell me how to fill this element as an array

testdata = [
    {
        key: "one",
        y: 200
    },
    {
        key: "two",
        y: 300
    }
       ];

example:

testdata=[];
testdata[]="one";
testdata[]="two";

Upvotes: 1

Views: 18813

Answers (2)

Dhaval
Dhaval

Reputation: 2861

I think you want two dimensional JS array

var items = [[11,22],[33,44],[55,66]];
alert(items[0][0]); // 11;

Or i think you want dictionary object like following

var dict = []; // create an empty array

dict.push({
    key:   "keyName",
    value: "the value"
});

reference taken from : How to create dictionary and add key value pairs dynamically in Javascript

Upvotes: 0

Hrishi
Hrishi

Reputation: 7138

It's much better to write a function that constructs a json object. Call it CreateObject and then you can just use a for loop like:

var list = [];
for(var i = 0; i < 10; i++) {
   var obj = CreateObject(i); //add other params if you need
   list.push(obj);
}
return list;

Upvotes: 1

Related Questions