Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save jackbillstrom/8d356dbcfb51b67a01c3652e64b5b16b to your computer and use it in GitHub Desktop.
Save jackbillstrom/8d356dbcfb51b67a01c3652e64b5b16b to your computer and use it in GitHub Desktop.
😠
var data = [{
id: 7485,
name: "Klädseltvätt",
categories: [{
id: 189,
name: "Tjänster",
slug: "services"
}, {
id: 207,
name: "Rekond",
slug: "rekond"
}]
}, {
id: 7456,
name: "Hankook Kinergy Eco 2 K435 185/60-14 H",
categories: [{
id: 28,
name: "Sommardäck",
slug: "sommardack"
}]
}]
let computed = data.filter((group) => {
let _name
let _group = []
let _temp
if(group.categories.map((item)=>{
_name = item.name
_temp = group.name
debugger
_group.push(group)
return item
}).length>0){
group.name = _name
group.products = _group
return group
debugger
}
})
console.log(computed)
@jackbillstrom
Copy link
Author

function (products) => {
  // reduce down each product into a category map
  // reducera varje produkt till en kategori.Map()
  const productsGroupedByCategory = products.reduce((categories, product) => {
    // insert the current product into each of the categories it contains
    product.categories.forEach(category => {
      // if the category exists in the map, we just need to append the current product
      if (category.id in categories)
        categories[category.id].products.push(product)
      else // otherwise, create a new category object with the current product
      categories[category.id] = ({ ...category, products: [product] })
    })
    return categories
  }, ({}))

  // convert the object into an array of objects
  return Object.values(productsGroupedByCategory)
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment