How to count the occurance of a field in JSON resp

Hi, I’m trying to count the number of “Name” of the car under Subcategories array (Number of occurrence of Name field with car name) . I have written the code but seems like count is not incrementing. Below is the sample response:

{
    "Name": "Cars",
    "Number": "0001-0268-",
    "Path": "/Trade-Me-Motors/Cars",
    "Subcategories": [
        {
            "Name": "Alfa Romeo",
            "Number": "0001-0268-0269-",
            "Path": "/Trade-Me-Motors/Cars/Alfa-Romeo",
            "HasClassifieds": true,
            "AreaOfBusiness": 3,
            "IsLeaf": true
        },
        {
            "Name": "Aston Martin",
            "Number": "0001-0268-0270-",
            "Path": "/Trade-Me-Motors/Cars/Aston-Martin",
            "HasClassifieds": true,
            "AreaOfBusiness": 3,
            "IsLeaf": true
        },
        {
            "Name": "Audi",
            "Number": "0001-0268-0271-"
        {
     ]
}

Please use the preformatted text option in the editor when posting code or JSON. It stops everything aligning to the left.

You haven’t included what you’ve tried so far?

I can think of two ways of doing this.

  1. Just count the number of objects in the Subcategories array using the length method that is available on all arrays.
  2. Map all of the “Name” values to a new array and use the length method again.
const response = pm.response.json();

let countV1 = response.Subcategories.length
console.log(countV1);

let countV2 = (response.Subcategories.map(obj => obj.Name)).length;
console.log(countV2);

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.