Home > Software design >  How to group by with two field in Javascript
How to group by with two field in Javascript

Time:10-13

I need to group by categorycode and categorname and other fields to add with object. sample data:

[
   {
      "categoryCode":"categoryCode1",
      "categoryName":"categoryName1",
      "cat_type":A
   },
   {
      "categoryCode":"categoryCode1",
      "categoryName":"categoryName1",
      "cat_type":B
   },
   {
      "categoryCode":"categoryCode2",
      "categoryName":"categoryName2",
      "cat_type":B
   }
]

though javascript I need to expected output :

[
   {
      "categoryCode":"categoryCode1",
      "categoryName":"categoryName1",
      "cat_type":[A,B]
   },
   {
      "categoryCode":"categoryCode2",
      "categoryName":"categoryName2",
      "cat_type":[B]
   }
]

how to achieve this.

CodePudding user response:

You can achieve that with reduce.

const arr = [{
    "categoryCode": "categoryCode1",
    "categoryName": "categoryName1",
    "cat_type": "A"
  },
  {
    "categoryCode": "categoryCode1",
    "categoryName": "categoryName1",
    "cat_type": "B"
  },
  {
    "categoryCode": "categoryCode2",
    "categoryName": "categoryName2",
    "cat_type": "B"
  }
]

const result = Object.values(
  arr.reduce((a, {
    categoryCode,
    categoryName,
    cat_type
  }) => (((a[`code_${categoryCode}_name_${categoryName}`] ??= {
    categoryCode,
    categoryName,
    cat_type: []
  }).cat_type.push(cat_type)), a), {})
);
console.log(result)

  • Related