I'm pulling from a large data dump API and need to filter the data better. Currently, this is an example of what I am seeing.
{
AA-Short: "information",
AA-Long: "more information",
AA-Extra: "even more information",
BB-Short: "information",
BB-Long: "more information",
BB-Extra: "even more information",
}
I'm trying to make this:
{
AA: {
AA-Short: "information",
AA-Long: "more information",
AA-Extra: "even more information"
},
BB: {
BB-Short: "information",
BB-Long: "more information",
BB-Extra: "even more information"
}
}
Here is an example of how it can be done:
const data = {
"AA-Short": "information",
"AA-Long": "more information",
"AA-Extra": "even more information",
"BB-Short": "information",
"BB-Long": "more information",
"BB-Extra": "even more information",
};
const dataKeys = Object.keys(data);
const groupedData = dataKeys.reduce((result, currKey) => {
// Pull out the group name from the key
const group = currKey.split('-')[0];
// Check if the group exists, if not, create it
const hasGroup = result[group] !== undefined;
if (!hasGroup)
result[group] = {};
// Add the current entry to the result
result[group][currKey] = data[currKey];
return result;
}, {});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With