P Tart
P Tart

Reputation: 9

How can I count the number of items in array

Below is JSON body returned from an API call. I'm using Postman and want to create a test using JavaScript to count the number of objects ("id"s) in the JSON returned. Something like tests["Only 1 login"] = objects=1 is a PASS, else Fail.

[
  {
    "id": 243,
    "user_id": 76,
    "account_id": 1,
    "unique_id": "12345",
    "special_user_id": null,
  },
  {
    "id": 244,
    "user_id": 84,
    "account_id": 1,
    "unique_id": "123456",
    "special_user_id": "staff_123456",
  }
]

Upvotes: 0

Views: 4490

Answers (3)

Ryan
Ryan

Reputation: 14649

You can use a for loop to iterate if you need to ONLY count the number of times an id property is set upon EACH object in the array.

var ids = []

for(var i = 0; i < obj.length; i++) {
    if(typeof entry.id !== 'undefined') {
        ids.push(entry[i].id);
    }
}

console.log(ids.length)

You can also just use obj.length if every object in the array is guaranteed to have an id property. You said count the number of ids, that's why the above for loop was implemented, just to be safe.

Upvotes: 0

user663031
user663031

Reputation:

If the JSON is still a string and you need to parse it:

var data = JSON.parse(json);

If you just want to know the number of elements in the array:

data.length

If some elements might be missing ids, and you don't want to count them:

data.filter(elt => 'id' in elt).length

Upvotes: 0

kevin ternet
kevin ternet

Reputation: 4612

Or just a count while reading through the array

var count = 0;
ids.forEach(x => {if (x.id != undefined) count++});
console.log(count); // 2

Upvotes: 1

Related Questions