Why can't I access the properties in this nested object?

Everything I read online regarding this issue says the nested object doesn’t exist, but it seems to exist in my console logs. Why doesn’t it exist?


function nestedArr(a) {
    var obj = {};
    for (var x = 0; x < a.length; x++){
        for (var y = 0; y < a[x].length; y++){
            var value = a[x][y];
            obj[value] = {row : x, col : y};
        }
    }

    console.log(obj); 
/*{ '1': { row: 0, col: 0 },
    '2': { row: 0, col: 1 },
    '3': { row: 0, col: 2 },
    '4': { row: 1, col: 0 },
    '5': { row: 1, col: 1 },
    '6': { row: 1, col: 2 },
    '7': { row: 2, col: 0 },
    '8': { row: 2, col: 1 },
    '9': { row: 2, col: 2 } }*/
    
    console.log(obj[1]); //{ row: 0, col: 0 }
    
    console.log(obj[1].row); //TypeError: Cannot read property 'row' of undefined

    console.log(obj[1]["row"]); //TypeError: Cannot read property 'row' of undefined
}

1 and '1' are not the same thing.

1 Like

Thanks for the speedy response. I have tried using “1” also with no success. Should that work?

It should.
Here is an example of it working:

1 Like

Hmm I’m trying to solve interview questions on a site called www.codefights.com much like the FCC algorithm challenges and I just copy/pasted the contents of the code you just posted and got the same problem as before. Very confusing :confused:. Thanks for verifying that it isn’t the code at least!

Edit : It’s working! It seems that single quotes do the job, not sure if this is a quirk of the site or something that would pop up generally. Thanks again!