Search code examples
javascriptloopsjavascript-objects

Why can’t I access object properties in a for-in loop over an array of objects?


I am currently utilizing the SheetSU API to read data from a Google Sheets file.

var members = Sheetsu.read("URL", {}, successFunc);

For now, the successFunc is a function that takes the input data to console.log() to me.

The data imports like this: (14){{..},{..},{..}....} and each object within this dictionary looks something like this:

0: {Name: "First Last", ID: "12536723", Status: "Member"}
1: {Name: "First Last", ID: "12371238", Status: "Member"}
...
14: {Name: "First Last", ID: "12341228", Status: "Member"}

I need to pull out the values of Name and ID, however:

for (var x in data) {
    console.log(x)
}

= 0, 1, 2, ..., 14 (as ints not objects)

for (var x in data) {
    console.log(x.Name)
}

= undefined, undefined, ..., undefined


Solution

  • x is not a value It is a index like 0,1 ...14, you can use of for that or use data[x] inside in.

    var data = [{
            Name: "First Last",
            ID: "12536723",
            Status: "Member"
        }, {
            Name: "First Last",
            ID: "12371238",
            Status: "Member"
        },
        {
            Name: "First Last",
            ID: "12341228",
            Status: "Member"
        }
    ]
    
    for (var x in data) {
    
        console.log(data[x].Name); //x is not a value It is a index like 0,1 ...14
    
    }
    
    for (var x of data) {
    
        console.log(x.Name); // use of which prints x as object not index
    
    }