I need to filter objects by their status id. I also need data and csr counts for each item. There are multiple items for each StatusName
:
[
{
"StatusId": 2,
"StatusName": "ordered",
"CSR_NameId": 2,
"CSR_Name": "test"
},
{
"StatusId": 3,
"StatusName": "delivered",
"CSR_NameId": 3,
"CSR_Name": "test2"
},
{
"StatusId": 5,
"StatusName": "created",
"CSR_NameId": 2,
"CSR_Name": "test"
},
{
"StatusId": 27,
"StatusName": "quoted",
"CSR_NameId": 2,
"CSR_Name": "test"
}
]
I need output like this:
[
{
"ordered":{
"all": 2,
"test": 1,
"test2": 1
},
"delivered": {
"all": 3,
"test": 2,
"test2": 1
},
"created": {
"all": 2,
"test": 2
},
"quoted": {
"all": 1,
"test": 1
}
}
]
I tried like this and I encountered this output:
// get unique ID
datas.forEach(i => !uniq.includes(i.StatusId) ? uniq.push(i.StatusId) : '' );
// filter by ID
uniq.forEach(id => {
res.push(datas.filter(o => o.StatusId === id));
})
[ [ { StatusId: 2, StatusName: 'ordered', CSR_NameId: 2, "CSR_Name": "test"}, { StatusId: 2, StatusName: 'ordered', CSR_NameId: 3, "CSR_Name": "test2" } ], [ { StatusId: 3, StatusName: 'delivered', CSR_NameId: 3, "CSR_Name": "test2" }, { StatusId: 3, StatusName: 'delivered', CSR_NameId: 2, "CSR_Name": "test" }, { StatusId: 3, StatusName: 'delivered', CSR_NameId: 2, "CSR_Name": "test" } ], [ { StatusId: 5, StatusName: 'created', CSR_NameId: 2, "CSR_Name": "test" }, { StatusId: 5, StatusName: 'created', CSR_NameId: 2, "CSR_Name": "test" } ], [ { StatusId: 27, StatusName: 'quoted', CSR_NameId: 2, "CSR_Name": "test" } ] ]
I need to fix this javascript code. I used forEach method and going to result. But I cannot do anything then.
2
Answers
You can use
Array#reduce
with an object that contains the counts for each type, updated on each iteration.