如何从对象数组中读取属性值?

时间:2016-01-31 07:45:31

标签: javascript node.js

我在node.js工作。

我在.js文件中进行了如下的休息api调用:

$http.get("/api/products/"+cat_id).success(
            function(response){
                //$scope.cat_id = response;
                console.log("Got response products for page 1");
                console.log("Received products for cat :"+response.pdt.cat_id);
            }
)

以下代码段包含在app.js文件中:

app.get('/api/products/:cat', function(req, res){
var pdts = [];

for(var i=0; i<=6; i++){
    var pdt = {
        id : "1" + i
        , name: 'Product' + i
        ,cat_id: req.params.cat
    };
    pdts.push(pdt);
}

res.json(pdts);
}); 

对象数组 pdts 通过最后一个语句作为响应发送。

现在我如何访问对象 pdt ??

的各个属性

的结果
console.log("Received products for cat :"+response.pdt.cat_id);

Cannot read property 'cat_id' of undefined

1 个答案:

答案 0 :(得分:2)

您正在返回一个对象数组,因此您需要遍历它并分别访问每个元素:

$http.get("/api/products/" + cat_id).success(function(response) {
    console.log("Got response products for page 1");

    // response is an array of javascript objects
    for (var i = 0; i < response.length; i++) {
        var element = response[i];
        console.log("Received products for cat :" + element.cat_id);
    }
});

或者如果您想通过索引直接访问某些元素:

console.log("Received products for cat :" + response[0].cat_id);

显然,建议您首先检查数组的大小,以确保您尝试访问的元素存在。