[Vuejs]-VueJS Reducing JSON return data by category and sum associated values

1👍

Without a library… take note of Object.values()

const rawData = [
    { category: "january", quantities: "2" },
    { category: "february", quantities: "2" },
    { category: "january", quantities: "2" },
    { category: "february", quantities: "2" },
    { category: "january", quantities: "2" },
    { category: "february", quantities: "2" },
    { category: "january", quantities: "2" },
    { category: "february", quantities: "2" }
];

const formattedData = rawData.reduce((previousValue, { category, quantities }) => {
    if (!previousValue[category]) {
        previousValue[category] = { category, totalQuantity: 0 };
    }
    previousValue[category].totalQuantity += +quantities;
    return previousValue;
}, {});

console.log(Object.values(formattedData));

Leave a comment