Sohan Shirodkar
Sohan Shirodkar

Reputation: 520

How to read attribute values from an array of objects?

I am working in node.js.

I make a rest api call in .js file as follows:

$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);
            }
)

The following code snippet is contained in a file 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);
}); 

The array of objects pdts is sent as a response through the last statement.

Now how do I access the individual attributes of my object pdt??

The result of

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

is

Cannot read property 'cat_id' of undefined

Upvotes: 1

Views: 95

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1039308

You are returning an array of objects, so you need to loop through it and access each element individually:

$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);
    }
});

or if you wanted to access some element directly by index:

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

Obviously it is recommended that you first check the size of the array to ensure that the element you are trying to access exists.

Upvotes: 2

Related Questions