Last active
August 29, 2015 14:00
-
-
Save chrisbuttery/11362933 to your computer and use it in GitHub Desktop.
Re-construct and categorise array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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"} | |
]; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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