JSFiddle - React, Tailwind, and code Playground
by chandings
JavaScript
let data = [
{
"Type": "INTRUSION",
"SiteId": "SITE_1",
},
{
"Type": "INTRUSION",
"SiteId": "SITE_1",
},
{
"Type": "INTRUSION",
"SiteId": "SITE_1",
},
{
"Type": "INTRUSION",
"SiteId": "SITE_2",
},
{
"Type": "INTRUSION",
"SiteId": "SITE_3",
},
{
"Type": "Fire",
"SiteId": "SITE_1",
},
{
"Type": "Fire",
"SiteId": "SITE_2",
},
{
"Type": "Fire",
"SiteId": "SITE_3",
},
{
"Type": "Smoke",
"SiteId": "SITE_1",
},
{
"Type": "Smoke",
"SiteId": "SITE_2",
},
{
"Type": "Smoke",
"SiteId": "SITE_3",
},
]
const obj = {};
for (let dt of data) {
const { Type, SiteId } = dt;
if (obj[Type]) {
const x = obj[Type].find((e) => {
return e.siteName === SiteId;
});
console.log(x)
if (x) {
const newArr = obj[Type].map(e => {
if(e.siteName === SiteId){
return {...e, count: ++e.count}
}else{
return e
}
})
obj[Type] = newArr
} else {
obj[Type].push({ siteName: SiteId, count: 1 });
}
} else {
obj[Type] = [{ siteName: SiteId, count: 1 }];
}
}
console.log(obj)
/*
let data = [
{
"Type": "INTRUSION",
"SiteId": "SITE_1",
},
{
"Type": "INTRUSION",
"SiteId": "SITE_1",
},
{
"Type": "INTRUSION",
"SiteId": "SITE_1",
},
{
"Type": "INTRUSION",
"SiteId": "SITE_2",
},
{
"Type": "INTRUSION",
"SiteId": "SITE_3",
},
{
"Type": "Fire",
"SiteId": "SITE_1",
},
{
"Type": "Fire",
"SiteId": "SITE_2",
},
{
"Type": "Fire",
"SiteId": "SITE_3",
},
{
"Type": "Smoke",
"SiteId": "SITE_1",
},
{
"Type": "Smoke",
...