0

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
            }
}
Noman Ali
  • 3,160
  • 10
  • 43
  • 77
  • Multidimensional arrays are a pain in javascript sometimes.. https://stackoverflow.com/questions/966225/how-can-i-create-a-two-dimensional-array-in-javascript – Roy Berris Sep 19 '17 at 14:10

3 Answers3

2

You need an object before accessing a property of it.

indexes[i] = indexes[i] || {}
indexes[i]['indexis'] = i;
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
2

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']

Nicholas Tower
  • 72,740
  • 7
  • 86
  • 98
0

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);
            }
}
Satish
  • 696
  • 1
  • 11
  • 22