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

Time:04-20

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!

CodePudding user response:

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.

  • Related