简体   繁体   English

如何在JavaScript对象中定位属性

[英]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. 我尝试将“ for in”循环中的“ productCode”属性与变量进行匹配。 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. 然后我只是尝试访问“ name”或“ price”属性,但是尽管我确实与“ productCode”属性匹配,但作为回报,我只会得到“ undefined”。

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. a是包含属性名称的字符串 It isn't the value of that property. 这不是该属性的值。 You need to get the value first. 您需要首先获得价值。

products.productType1[a].name

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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