0

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",
  }
]
2
  • I do not understand what you mean by tests["Only 1 login"] or how it connects to PASS and FAIL. Do you mean you want to see if there is one element in the array? Is the array already parsed into a JS object, or are you stuck on how to do that (hint: JSON.parse). For getting the number of items in the array (usually known as its "length"), see MDN. Commented Jul 26, 2016 at 18:50
  • Please review your answers and accept one. Commented Jul 29, 2016 at 20:55

3 Answers 3

1

Or just a count while reading through the array

var count = 0;
ids.forEach(x => {if (x.id != undefined) count++});
console.log(count); // 2
Sign up to request clarification or add additional context in comments.

1 Comment

This seems to be getting me on the right track. In a Postman test, would I use tests["User has only 1 login."] = count=1?
0

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

2 Comments

What id id is 0.. or say falsey ?
in doesn't care for the value of id. It cares that id is a property upon elt
0

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.

11 Comments

Just INPUT_ARRAY.length ?
@Rayon I guess if it's guaranteed they will all have the id property
In your answer, if it does not have, undefined will be pushed hence makes no sense...
What is entries? Assuming you meant to say ids, how is what you are logging different from obj.length? if you want to create an array of ids for whatever reason, why not obj.map(e => e.id)?
entries is the name of his object that he didn't give a name for
|

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.