0

I have a JSON I would like to re-arrange my data, so that I can group all items by category name. Here is my data.

[
  {
    "id":317,
    "name":"Ingram's Camphor Cream",
    "slug":null,
    "product_category_id":15,
    "industry_id":2,
    "deleted_at":null,
    "category":{
      "id":15,
      "name":"Skincare",
      "slug":null,
      "industry_id":2,
      "deleted_at":null,
      "sku_id":3,
      "is_active":1
    },
  },
  {
    "id":323,
    "name":"Zimgold",
    "slug":null,
    "product_category_id":2,
    "industry_id":2,
    "category":{
      "id":2,
      "name":"Cooking Oils",
      "slug":null,
      "industry_id":2,
      "sku_id":2,
      "is_active":1
    }
  }
]

I would like to have a result like so:

[
   'Skincare': [ {}],
   'Cooking Oils': [{}]
]

Thank you in advance. I would really appreciate your help.

3 Answers 3

1

You can reduce the array of products to a map of names to product arrays with a reducer like this:

const grouped = products.reduce((grouped, product) => {
  const key = product.category.name
  // replace the array at [key] with a new one including the current element
  return { ...grouped, [key]: (grouped[key]??[]).concat(product)}
}, {})
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks but how do i make the result an array rather than an object.
I assumed the square brackets were a typo, since arrays don't have string keys. If you want to iterate over all groups, you can use Object.entries(grouped). This will return an array of [key: string, value: Product[]] pairs.
I submitted an edit suggestion for what I thought was a typo in your result example before I read your comment. Could you make some minor edit to your question so my suggestion gets rejected automatically?
1

Maybe there is a a prettier way but something like this would work

 var groupedData = {};

    data.forEach(item => {
        if (!groupedData[item.category.name]) {
            groupedData[item.category.name] = [];
        }
        groupedData[item.category.name].push(item);
    })

Comments

0
arr.map(item=>{
    let key = item.category.name
    return {[key]:item}
})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.