Skip to content

Instantly share code, notes, and snippets.

@chrisbuttery
Last active August 29, 2015 14:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chrisbuttery/11362933 to your computer and use it in GitHub Desktop.
Save chrisbuttery/11362933 to your computer and use it in GitHub Desktop.
Re-construct and categorise array
var data = [
{price: "$99.99", stocked: true, name: "iPod Touch", category: "Electronics"},
{price: "$399.99", stocked: false, name: "iPhone 5", category: "Electronics"},
{price: "$199.99", stocked: true, name: "Nexus 7", category: "Electronics"},
{price: "$49.99", stocked: true, name: "Football", category: "Sporting Goods"},
{price: "$9.99", stocked: true, name: "Baseball", category: "Sporting Goods"},
{price: "$29.99", stocked: false, name: "Basketball", category: "Sporting Goods"}
];
var productList = [];
var category = {};
var products = [];
var lastCategory = null;
data.map(function(product){
if (lastCategory !== product.category) {
// reset array and obj
if (prods.length) {
products = [];
category = {};
}
category.name = product.category;
category.products = products;
productList.push(category);
lastCategory = product.category;
}
category.products.push(product);
});
//console.log(productList);
return productList;
// productList
[
{
name:"Electronics",
products:[
{price:"$99.99", stocked:true, name:"iPod Touch", category:"Electronics"},
{price:"$399.99", stocked:false, name:"iPhone 5", category:"Electronics"},
{price:"$199.99", stocked:true, name:"Nexus 7", category:"Electronics"}
]
},
{
name:"Sporting Goods",
products:[
{price:"$49.99", stocked:true, name:"Football", category:"Sporting Goods"},
{price:"$9.99", stocked:true, name:"Baseball", category:"Sporting Goods"},
{price:"$29.99", stocked:false, name:"Basketball", category:"Sporting Goods"}
]
}
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment