creating list of objects in Javascript

Javascript

Javascript Problem Overview


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

Javascript Solutions


Solution 1 - Javascript

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);

Solution 2 - Javascript

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

Solution 3 - Javascript

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]);
}

Solution 4 - Javascript

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;
});

Solution 5 - Javascript

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)}
    });

Solution 6 - Javascript

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser517406View Question on Stackoverflow
Solution 1 - JavascriptDarin DimitrovView Answer on Stackoverflow
Solution 2 - Javascripttbradley22View Answer on Stackoverflow
Solution 3 - JavascriptnachoView Answer on Stackoverflow
Solution 4 - JavascriptBlexyView Answer on Stackoverflow
Solution 5 - Javascriptthat one guy on the internetView Answer on Stackoverflow
Solution 6 - JavascriptDVeenView Answer on Stackoverflow