user517406
user517406

Reputation: 13773

creating list of objects in Javascript

Is it possible to do create a list of your own objects in Javascript? This is the type of data I want to store :

Date : 12/1/2011   Reading : 3   ID : 20055    
Date : 13/1/2011   Reading : 5   ID : 20053    
Date : 14/1/2011   Reading : 6   ID : 45652

Upvotes: 130

Views: 713394

Answers (6)

Instantiate the array

  list = new Array()

push non-undefined value to the list

    var text = list.forEach(function(currentValue, currentIndex, listObj) {
    if(currentValue.text !== undefined)
    {list.push(currentValue.text)}
    });

Upvotes: 0

Nick Blexrud
Nick Blexrud

Reputation: 9603

Going off of tbradley22's answer, but using .map instead:

var a = ["car", "bike", "scooter"];
a.map(function(entry) {
    var singleObj = {};
    singleObj['type'] = 'vehicle';
    singleObj['value'] = entry;
    return singleObj;
});

Upvotes: 8

DVeen
DVeen

Reputation: 13

So, I'm used to using

var nameOfList = new List("objectName", "objectName", "objectName")

This is how it works for me but might be different for you, I recommend to watch some Unity Tutorials on the Scripting API.

Upvotes: -6

nacho
nacho

Reputation: 591

Maybe you can create an array like this:

var myList = new Array();
myList.push('Hello');
myList.push('bye');

for (var i = 0; i < myList .length; i ++ ){
    window.console.log(myList[i]);
}

Upvotes: 29

tbradley22
tbradley22

Reputation: 1545

dynamically build list of objects

var listOfObjects = [];
var a = ["car", "bike", "scooter"];
a.forEach(function(entry) {
    var singleObj = {};
    singleObj['type'] = 'vehicle';
    singleObj['value'] = entry;
    listOfObjects.push(singleObj);
});

here's a working example http://jsfiddle.net/b9f6Q/2/ see console for output

Upvotes: 74

Darin Dimitrov
Darin Dimitrov

Reputation: 1038730

var list = [
    { date: '12/1/2011', reading: 3, id: 20055 },
    { date: '13/1/2011', reading: 5, id: 20053 },
    { date: '14/1/2011', reading: 6, id: 45652 }
];

and then access it:

alert(list[1].date);

Upvotes: 189

Related Questions