0

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

3
  • 1
    arr only contains 2 elements, that you get with arr[0] and arr[1] but when you try to get a 3rd, non-existant element with arr[2] you get undefined and then you try to access a property of undefined which gives you that TypeError Commented Jun 18, 2017 at 21:55
  • @MikaelLennholm How do I create a 2D array with no limit on elements? Commented Jun 18, 2017 at 21:56
  • See Musa's answer. Arrays don't have a set number of elements nor a maximum number of elements, you can add and remove from an array freely Commented Jun 18, 2017 at 22:00

1 Answer 1

2

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]);
})
Sign up to request clarification or add additional context in comments.

3 Comments

I would also suggest using the index provided by the forEach() function instead of creating your own counter
I see javascript handles arrays differently than most other languages. The square brackets depict separate arrays instead of dimensions.
@Arpit Yes, arrays in Javascript are just objects with some dedicated syntactic sugar. There are no true arrays in JS.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.