Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter JavaScript object by key's prefix and reduce to build new objects [closed]

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"
  }
} 
like image 377
WhosDustin Avatar asked May 17 '26 01:05

WhosDustin


1 Answers

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;
}, {});
like image 120
Rob Brander Avatar answered May 19 '26 14:05

Rob Brander