Rachel
Rachel

Reputation: 727

How to count the number of array of object id's and increment

probably an easy question but a bit stumped, given this JSON structure:

{
    "users": [{
        "action": "update",
        "payload": [{
                "id": "1",
                "name": "Albin Jaye"
            },
            {
                "id": "2",
                "name": "Dave Mustaine"
            }
        ]
    }],

I am testing a conditional for the users key, and then of course for creating a new entry in another file for payload I need to increment the id counter So, I have been trying this, but not working:

if(actionDetail.action === 'create') {
    console.log('This is a CREATE entry');
    var size = Object.keys(actionDetail.payload[0]).length;
    console.log(size);
}

of course this doesn't work, I don't need the number of keys, I just simply need to know how to count the total numbers of objects in the payload array of objects (2 total) not sure how to do this? I am guessing a nifty use of .reduce() could do it, or similar? i.e. set a const to the reduce() and then add +1 so I have 3 in the variable for new record to be added!

Upvotes: 0

Views: 832

Answers (1)

Ashishssoni
Ashishssoni

Reputation: 819

You can simply use array.length to get the total length of an array.

In your question, you just need to change one simple part to get the length of payload array.

  var size = actionDetail.payload.length;

You can also read about array.length here, let me know if you have doubts.

Upvotes: 1

Related Questions