Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

creating list of objects in Javascript

Tags:

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 
like image 961
user517406 Avatar asked May 03 '11 11:05

user517406


People also ask

Can we create list in JavaScript?

List does not works on javascript.

Can you have an array of objects in JavaScript?

Creating an array of objectsWe can represent it as an array this way: let cars = [ { "color": "purple", "type": "minivan", "registration": new Date('2017-01-03'), "capacity": 7 }, { "color": "red", "type": "station wagon", "registration": new Date('2018-03-03'), "capacity": 5 }, { ... }, ... ]


2 Answers

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); 
like image 88
Darin Dimitrov Avatar answered Nov 15 '22 23:11

Darin Dimitrov


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

like image 43
tbradley22 Avatar answered Nov 15 '22 22:11

tbradley22