Timothy Frisch
Timothy Frisch

Reputation: 2809

Iterating through object properties in Javascript

I have a set of properties inside of a javasript object.

    var leanToolButtonStatus = {
    FiveSStatus:0,
    SmallLotStatus:0,
    SmedStatus:0,
    QualityStatus:0,
    CellsStatus:0,
    CrossTrainStatus:0,
    SelfDirectedStatus:0,
    PMStatus:0,
    VendorStatus:0,
    SmallPurchaseStatus:0,
    NewEquipmentStatus:0,
    MarketStatus:0,
    KanbanStatus:0
}

Now I want to run a for-loop to iterate over that so I try:

  function loopThroughObject(){
    var iterationCounter = 0;
    for(var x = 0; x<1; x++){
        for(var y = 0; y<6; y++){
        switch(leanToolButtonStatus[iterationCounter]) {
            case 0:
                break;
            case 1:
                break;
            case 2:
                break;
            }
        }
        iterationCounter++;
    }
}

However I get the following error:

Uncaught SyntaxError: Unexpected number.

Any ideas where I am going wrong?

Upvotes: 0

Views: 69

Answers (3)

Lee
Lee

Reputation: 859

It should work with this codesnippet:

for(key in list)
{
 var elementOfList = list[key];
}

key could be 'FiveSStatus' and elementOfList 0

Upvotes: 2

Sudhir Bastakoti
Sudhir Bastakoti

Reputation: 100205

if the structure of your object is exactly like you added in your question, you wont need for loop, just access it as :

var leanToolButtonStatus = {
    FiveSStatus:0,
    SmallLotStatus:0,
    SmedStatus:0,
    QualityStatus:0,
    CellsStatus:0,
    CrossTrainStatus:0,
    SelfDirectedStatus:0,
    PMStatus:0,
    VendorStatus:0,
    SmallPurchaseStatus:0,
    NewEquipmentStatus:0,
    MarketStatus:0,
    KanbanStatus:0
};
console.log(leanToolButtonStatus["FiveSStatus"]);

if you dont know the key names. you can use for..in loop, as:

for(val in leanToolButtonStatus ) {
    console.log(leanToolButtonStatus[val]);
}

Upvotes: 2

Oleksandr T.
Oleksandr T.

Reputation: 77522

#1
for (var key in leanToolButtonStatus) {
   leanToolButtonStatus[key]
}

#2
Object.keys(leanToolButtonStatus).forEach(function (key) {
    leanToolButtonStatus[key]
});

Upvotes: 1

Related Questions