[{
"project_name": "test",
"status": "High"
},{
"project_name": "test",
"status": "Critical"
},{
"project_name": "test",
"status": "Critical"
}]
I tried a lot with Object.entries, but I couldn't reach the result I wanted.
Expected Output
[{
project_name: "test",
value: 1,
status: "High",
},
{
project_name: "test",
value: 2,
status: "Critical",
}]
What I want to do is not add a value, but consider more objects in the first array with the same status values. I want to count and group them all.
product_name and the status.Object.values to get at the new objects from the temporary array.const data=[{project_name:"test",status:"High"},{project_name:"test",status:"Critical"},{project_name:"test",status:"Critical"}];
const temp = {};
for (const obj of data) {
const { project_name, status } = obj;
const key = `${project_name}-${status}`;
temp[key] ??= { ...obj, value: 0 };
temp[key].value += 1;
}
console.log(Object.values(temp));
Additional documentation
You can also use reduce. The same principles apply (but here you're just initialising an empty object for the accumulator, and passing that through to the next iteration of the array) though the loop might be simpler to understand if you're new to JS.
const data=[{project_name:"test",status:"High"},{project_name:"test",status:"Critical"},{project_name:"test",status:"Critical"}];
const out = data.reduce((acc, obj) => {
const { project_name, status } = obj;
const key = `${project_name}-${status}`;
acc[key] ??= { ...obj, value: 0 };
acc[key].value += 1;
return acc;
}, {});
console.log(Object.values(out));