Ekjon S
Ekjon S

Reputation: 51

javascript/jquery dynamic object array declaration

I've been away from javascript/jquery fro few years and now it feels like I can't find the simplest things. I have this object stations like:

var station = {
  stationId;
  stationName;
}

Now if I want an array of stations, can't I do like:

var stationList = new station [sizeofarray];

Looks like I can't and didnot find any straight forward answers on search.

Upvotes: 0

Views: 82

Answers (2)

P.S.
P.S.

Reputation: 16384

If you need to put only one object inside the array, you can simply do the following:

var station = {
  stationId: 'id',
  stationName: 'name'
}
var stationList = [station];
console.log(stationList);

If you need to put more than one element, or the array is not empty, you can push the object to the end of the array (it doesn't make sense if you need to put only one object to the array):

var station = {
  stationId: 'id',
  stationName: 'name'
}
var stationList = [];

stationList.push(station);
console.log(stationList);

Or to the start of the array:

var station = {
  stationId: 'id',
  stationName: 'name'
}
var stationList = [];

stationList.unshift(station);
console.log(stationList);

Upvotes: 1

Jesus Carrasco
Jesus Carrasco

Reputation: 1354

var stationList = [{stationId:1, stationName:''}];

this create an array with one object inside.

If want push anoder object just. push to array like this

stationList.push({stationId:2, stationName:'otherName'});

Upvotes: 1

Related Questions