0

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?

1
  • Since you are using a for in loop to your object. Consider using hasOwnProperty to edge your loop. Commented Jul 18, 2015 at 9:09

1 Answer 1

3

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

Comments

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.