[
{
"branchCode": "111",
"referenceNumber": "2222",
"comments": "Write Off",
"transactionDate": "2022-02-23T00:00:00",
"amount": 0,
"accountCode": "MMMM",
"accountName": "Metal MMMM",
"allocations": [
{
"branchCode": "111",
"referenceNumber": "3333",
"allocationDate": "2022-02-23T09:23:57",
"ledgerTypeDescription": "Client",
"accountCode": "MMMM",
"accountName": "Metal MMMM",
"amount": -0.02
}
]
},
{
"branchCode": "222",
"referenceNumber": "33333",
"comments": "To write off historic med fee $0",
"transactionDate": "2022-03-24T00:00:00",
"amount": 0,
"accountCode": "OOOO",
"accountName": "Oranga OOOO - AEP",
"allocations": [
{
"branchCode": "222",
"referenceNumber": "456",
"allocationDate": "2022-03-24T10:39:02",
"ledgerTypeDescription": "Client",
"accountCode": "OOOOP",
"accountName": "Oranga 0000 - AEP",
"amount": 94.88
}
]
}
]
In the above JSON Response i need to find how many Allocations have been done in the entire Response. Can i do this using a for loop , If so how to use it to iterate through the Array and then count the Allocations item
I tried using the Object.keys(jsondata[0]).length) method. But this is useful to find the length of the items in a specific block. But i could not understand how to traverse through an array and find the number of allocations
Another option is to use flatMap()
to get all the allocations
on which you can call .length
:
const data = [{"branchCode": "111", "referenceNumber": "2222", "comments": "Write Off", "transactionDate": "2022-02-23T00:00:00", "amount": 0, "accountCode": "MMMM", "accountName": "Metal MMMM", "allocations": [{"branchCode": "111", "referenceNumber": "3333", "allocationDate": "2022-02-23T09:23:57", "ledgerTypeDescription": "Client", "accountCode": "MMMM", "accountName": "Metal MMMM", "amount": -0.02 } ] }, {"branchCode": "222", "referenceNumber": "33333", "comments": "To write off historic med fee $0", "transactionDate": "2022-03-24T00:00:00", "amount": 0, "accountCode": "OOOO", "accountName": "Oranga OOOO - AEP", "allocations": [{"branchCode": "222", "referenceNumber": "456", "allocationDate": "2022-03-24T10:39:02", "ledgerTypeDescription": "Client", "accountCode": "OOOOP", "accountName": "Oranga 0000 - AEP", "amount": 94.88 } ] } ];
const n = data.flatMap(o => o.allocations).length;
console.log(n);