1

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
1
  • 6
    since response is an array of pdts, it should be something like this response[0].cat_id Commented Jan 31, 2016 at 7:48

1 Answer 1

2

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.

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.