Jensej
Jensej

Reputation: 1305

How to create array of object in node.js

My Class look like this:

var Coin = {
    _id: null,
    createGame: function(id) {
     this._id = id;
    },
    start: function() {

    }
};

I'm trying to create an array of objects, but I can create only one. Could someone tell what i'm doing wrong?

I create array like this:

CoinArray = [];
CoinArray['123'] = new Coin.createGame(123);
CoinArray['333'] = new Coin.createGame(333);
CoinArray['333'].start

At the end I want to have array with object and for example I will take first el of array, and execute other method from Coin class.

Upvotes: 1

Views: 25323

Answers (2)

Angels
Angels

Reputation: 230

class Coin {
  constructor(id) {
    this._id = id;
  }
  start() {
    console.log('starting');
  }
}

CoinArray = [];
CoinArray['123'] = new Coin(123);
CoinArray['333'] = new Coin(333);
CoinArray['123'].start();

Also i would suggest managing id's that way:

let id = 0;
class Coin {
  constructor() {
    this._id = id++;
  }
  start() {
    console.log('starting');
  }
}

CoinArray = [];
CoinArray.push(new Coin());
CoinArray.push(new Coin());
CoinArray[0].start();

Upvotes: 2

Christos
Christos

Reputation: 53958

You need to push a newly created item to your array like below:

CoinArray.push(new Coin.Create('123)); 

On the other hand if you want to create an object with keys ids and values corresponding Coin objects, you should try this:

CoinDictionary = {};
CoinDictionary['123'] = new Coin.Create('123');

Note:

I think that you should refactor a bit the Coin if you want to use it as a constructor function:

function Coin(id){
    this.id = id;
}

Doing this change you can use it as below:

CoinArray.push(new Coin('123'));

function Coin(id){
    this.id = id;
}

var CoinArray = [];
CoinArray.push(new Coin('123'));
CoinArray.push(new Coin('456'));
CoinArray.push(new Coin('789'));

console.log(CoinArray);

Update

At the end I want to have array with object and for example I will take first el of array, and execute other method from Coin class.

For this purpose If I were you I would have gone with the creation of an object with keys the ids and values references to Coin objects:

function Coin(id){
    this.id = id;
}

Coin.prototype.start = function(){
    console.log("game with id "+this.id+" started.");
}

Coins = {}
Coins['123'] = new Coin('123');
Coins['456'] = new Coin('456');
Coins['789'] = new Coin('789');

Coins['456'].start();

Upvotes: 2

Related Questions