Home > front end >  Filter object array based on category and return list of matches React TS
Filter object array based on category and return list of matches React TS

Time:03-16

I am having trouble filtering an object array, based on a given property.

The object array looks something like this:

someData: [{
                id: "123",
                personData: [
                  {
                    personName: "John Smith",
                    personId: "125443",
                    categoryId: "B1",
                    description: "description"
                  }}]}];

I want to group the personData based on the categoryId, but represent the category grouping by its categoryName (instead of Id as this will not make much sense to the user).

There are a series of categories which are contained in a json in the following format:

const groups = {
  data: [
    {
      categoryName: "Banking",
      categoryId: "B1",
      description: "Financial sector"
    },
    {
      categoryName: "Retail",
      categoryId: "R1",
      description: "Retail and customer experience"
    }
  ]
};

How would I go about filtering based on these conditions? All help is much appreciated! I am using react and typescript

Once filtered the data should look like this:

Banking
    personName: John Smith
    personId: 125443

Retail
   personName: Judie Smith
   personId: 124938

CodePudding user response:

You can try groupBy on that person data.

const products = [
 { name: 'apples', category: 'fruits' },
 { name: 'oranges', category: 'fruits' },
 { name: 'potatoes', category: 'vegetables' }
];

const groupByCategory = products.groupBy(product => {
    return product.category;
});

console.log(groupByCategory);
// {
//   'fruits': [
//     { name: 'apples', category: 'fruits' }, 
//     { name: 'oranges', category: 'fruits' },
//   ],
//   'vegetables': [
//     { name: 'potatoes', category: 'vegetables' }
//   ]
// }

CodePudding user response:

I think something along the lines of this function would return what you need.

const data = [
    {
      categoryName: "Banking",
      categoryId: "B1",
      description: "Financial sector"
    },
    {
      categoryName: "Retail",
      categoryId: "R1",
      description: "Retail and customer experience"
    }
];

function groupByProperty(arrayOfObjects, property) {
  return arrayOfObjects.reduce((acc, curr) => {
    const key = curr[property];
    if (!acc[key] && acc[key] !== property) {
      acc[key] = [];
    }
    acc[key].push(curr);
    return acc;
  }, {});
}

const dataByCategoryName = groupByProperty(data, "categoryName");
console.log(dataByCategoryName);

/* Output
{
    Banking: [{
        categoryId: "B1",
        description: "Financial sector"
    }],
    Retail: [{
        categoryId: "R1",
        description: "Retail and customer experience"
    }]
}
*/
  • Related