Noman Ali
Noman Ali

Reputation: 3340

Two dimensional arrays populating does not work javascript

When i try to create two dimensional array in javascript using loop, it gives me following error:

Cannot set property 'indexis' of undefined

Code:

var indexes = [];
for (var i = 0; i < headingsArray.length; i++) {
            if (headingsArray[i].toLowerCase().indexOf('name') != -1) {
                indexes[i]['indexis'] = i;
                indexes[i]['headingis'] = headingsArray[i]; //assuming headingsArray exist
                indexes[i]['valueis'] = rows[0][i]; //assuming rows exist
            }
}

Upvotes: 0

Views: 87

Answers (3)

Satish
Satish

Reputation: 726

define temp var with field initialise to null & use push() function of JavaScript

for (var i = 0; i < headingsArray.length; i++) {
var temp={indexis: null,headingis:null,valueis:null};;
            if (headingsArray) {
                temp['indexis'] = i;
               temp['headingis'] = headingsArray[i]; //assuming headingsArray exist
                temp['valueis'] = rows[0][i];
                indexes.push(temp);
            }
}

Upvotes: 0

Nicholas Tower
Nicholas Tower

Reputation: 85102

You need to create the inner arrays/objects as well, or else index[i] is undefined, so index[i]['indexis'] will throw an exception.

var indexes = [];
for (var i = 0; i < headingsArray.length; i++) {
    indexes[i] = {}; //<---- need this
    if (headingsArray[i].toLowerCase().indexOf('name') != -1) {
        indexes[i]['indexis'] = i;
        indexes[i]['headingis'] = headingsArray[i]; 
        indexes[i]['valueis'] = rows[0][i];
    }
}

You described it as a multidimensional array, but you're using it as though it's an array of objects (because you're accessing named properties, instead of numbered properties). So my example code is creating objects on each iteration. If you meant to have an array of arrays, then do indexes[i] = [], and interact with things like indexes[i][0] rather than indexes[i]['indexis']

Upvotes: 2

Nina Scholz
Nina Scholz

Reputation: 386680

You need an object before accessing a property of it.

indexes[i] = indexes[i] || {}
indexes[i]['indexis'] = i;

Upvotes: 2

Related Questions