简体   繁体   中英

How to target property in JavaScript object

I have the following problem. I'm sure the solution is rather simple, but I just can't figure it out.

So there is a object which goes like this:

var products = {
    "productType1" : {
        "productCode" : {
            "name" : "Some Name 1",
            "price" : "250"
        },
        "productCode2" : {
            "name" : "Some Name 2",
            "price" : "300"
        },
        "productCode3" : {
            "name" : "Some Name 3",
            "price" : "330"
        }
    }
}

And I try to match a "productCode" property in a "for in" loop with a variable. And then I just try to access the "name" or "price" property but in return I only get "undefined", although I do get match with a "productCode" property.

for(a in products.productType1){
    if(finalCode === a){
        console.log(a.name);
        break;
    }
    else{
        console.log("This is not the property you're looking for");
        continue;
    }

So the question is - how can I access the above mentioned properties in a loop?

a is a string containing the property name. It isn't the value of that property. You need to get the value first.

products.productType1[a].name

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM