我在 node.js 工作。
我在 .js 文件中进行 rest 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
最佳答案
您正在返回一个对象数组,因此您需要遍历它并单独访问每个元素:
$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);
显然建议您首先检查数组的大小以确保您尝试访问的元素存在。
关于javascript - 如何从对象数组中读取属性值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35111513/