0

I need to call the API to get the data. Here is the current implementation.

return $.get(API_URL)
    .then(function (response) {
        return response.data;
    }, function (response) {
        return response.data;
    });

And when i console log value of the response. Have this.

console.log(response.data);
Output: [object Object]

When I check the Network->Response:

JSON
  Data
    0: Object
    1: Object
  Success: True

I need to count the number of object in the response. What should I do?

1
  • response.length ? Commented Sep 13, 2017 at 12:04

2 Answers 2

1
var responseData = JSON.parse(response.data.data)

this should give you an object with actual data

and then to count properties of that object with just vanilla JS (this is a lot easier if you use libs or frameworks with stuff like for each etc)

if (!Object.keys) {
Object.keys = function (obj) {
    var keys = [],
        k;
    for (k in obj) {
        if (Object.prototype.hasOwnProperty.call(obj, k)) {
            keys.push(k);
        }
    }
    return keys;
};
}

var numberOfProperties= Object.keys(obj).length;

Or in ES5 compatible environment you could use:

Object.keys(obj).length
Sign up to request clarification or add additional context in comments.

Comments

0

You could use jQuerys getJSON or explicietly tell that you want to receive something of the content type application/json (jQuery already tries to guess the type so this is should not be necessary). To get the Object values, regardless of their key values, do this:

function getMyObjects(){
  return $.getJSON(API_URL)
  .then(function processMyData(data) {
    // if data is an Object with only indices as keys:
    return Object.values(data);
  })
  .catch(console.log);
}

This will give you an Array where you can just use the length property

getMyObjects()
  .then(function(theArray){ 
     console.log(theArray.length); 
   })
   .catch(console.log);

If you want to do something with the keys, you can use

Object.keys(data).forEach(function(key){console.log(key, data[key])});

If you have to work with old browsers and without some polyfilling, use a for-in-loop, see here

More about jQuerys getJSON here

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.