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;

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!


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.

Answered By – Ashishssoni

Answer Checked By – Willingham (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.