Moiz
Moiz

Reputation: 2439

How to add a collection in Javascript objects

Hello I am creating a two dimensional array in javascript. the object looks like this.

totalCells = [
    lineNumber = 0,
    cells = []
 ];

How do I add that to this array ?

Can I do totalCells.push(1, ['a', 'b', 'c']);

But this throws me the error : cells is not defined

Upvotes: 0

Views: 253

Answers (3)

Bruno Grieder
Bruno Grieder

Reputation: 29864

As an alternative to Rory answer. Use an object

var totalCells = {}

Then you can directly add keys/properties:

totalCells[1] = ['a','b','c']
totalCells[2] = ['d','e','f']

The advantage with this is you can use your object as a Map:

totalCells[1] will return ['a','b','c']

Using underscore.js (or lodash), you can then do fancy manipulations like extract keys, etc....

Upvotes: 0

Oli
Oli

Reputation: 597

A simpler way to model your 2 dimensional array would be to use an array of arrays. e.g.

totalCells = [];

totalCells.push(['a','b','c']);
totalCells.push(['d','e','f']);

The line number is implicit, for example, in this case, totalCells[0] is the first line, etc.

Upvotes: 0

Rory McCrossan
Rory McCrossan

Reputation: 337627

You can't do what you're trying. If you want keys in an array use an object. Then you can do this:

var totalCells = {
    lineNumber: 0,
    cells: []
};

// some logic...

totalCells.lineNumber = 1;
totalCells.cells = ['a', 'b', 'c'];

Alternatively, you could have an array of objects which ties the cells directly to multiple lineNumbers:

var totalCells = [];

// some logic...

totalCells.push({
    lineNumber: 1,
    cells: ['a', 'b', 'c']
});

totalCells.push({
    lineNumber: 2,
    cells: ['x', 'y', 'z']
});

Upvotes: 3

Related Questions