Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Group json data by a property – vue.js

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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)}
}, {})
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading