Arpit
Arpit

Reputation: 109

JavaScript TypeError in 2D array

I'm trying to read value from a json into a 2D array

  var arr = [[],[]];
  var i = 0;
    var file = './test.json';
    jsonfile.readFile(file, function(err, objs) {
        let i = 0;
        objs.forEach(function (obj) {
            arr[i][0] = obj["outcount"];
            arr[i][1] = obj["gateID"];
            arr[i][2] = obj["timestamp"];
            arr[i][3] = obj["eventCode"];
            i = i + 1;
        });
        console.log(arr[2]);
    })

For i = 0 and i = 1, it works fine but on i = 2 it gives the error

TypeError: Cannot set property '0' of undefined

Upvotes: 0

Views: 59

Answers (1)

Musa
Musa

Reputation: 97672

Your array arr only has two items in it, the empty arrays.
So arr[0] is the first one and arr[1] is the second one that's all, arr[2] doesn't exist. If you had arr = [[],[],[]]; then arr[2] would work but you can see the problem there.
Best option is to create the sub-array before you use it.
Also, the forEach function provides a counter which can be used instead of creating your own.

var arr = [];
var file = './test.json';
jsonfile.readFile(file, function(err, objs) {
    objs.forEach(function (obj, i) {
        arr[i] = [];
        arr[i][0] = obj["outcount"];
        arr[i][1] = obj["gateID"];
        arr[i][2] = obj["timestamp"];
        arr[i][3] = obj["eventCode"];
        i = i + 1;
    });
    console.log(arr[2]);
})

Upvotes: 2

Related Questions