Tengo un JSON. Me gustaría reorganizar mis datos para poder agrupar todos los elementos por nombre de categoría. Aquí están mis datos.
[ { "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 } } ]Me gustaría tener un resultado como este:
[ 'Skincare': [ {}], 'Cooking Oils': [{}] ]Gracias de antemano. Realmente agradecería su ayuda.
Puede reducir la matriz de productos a un mapa de nombres a matrices de productos con un reductor como este:
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)} }, {})Tal vez haya una forma más bonita, pero algo como esto funcionaría.
var groupedData = {}; data.forEach(item => { if (!groupedData[item.category.name]) { groupedData[item.category.name] = []; } groupedData[item.category.name].push(item); })arr.map(item=>{ let key = item.category.name return {[key]:item} })