Open jeremypeter opened 5 years ago
Below we just received an array of products from Shopify's API. We now need to scrub the data and make it match the object that our custom service needs to consume.
var productsSold = [
{
brand: 'Guchee',
total: '90.34',
tag: 'purse'
},
{
brand: 'Louie Veeton',
total: '12.99',
tag: 'purse'
},
{
brand: 'Guchee',
total: '5.34',
tag: 'belt'
},
{
brand: 'Tommy Heelfiger',
total: '34.66',
tag: 'watch'
},
{
brand: 'Mycol Coors',
total: '3.33',
tag: 'belt'
},
{
brand: 'Guchee',
total: '23.20',
tag: 'purse'
}
];
// Create a function that categorizes each `brand` in an object.
// Within each brand object, categorize by `tag` and within that object
// calculate the total number of items sold.
// Final result should look something like the following:
// NOTE: the order of the properties doesn't matter
// {
// guchee: {
// purse: {
// totalSold: 113.54
// },
// belt: {
// totalSold: 5.43
// }
// },
// tommy_heelfiger: {
// watch: {
// totalSold: 34.66
// }
// },
// mycol_coors: {
// belt: {
// totalSold: 3.33
// }
// },
// louie_veeton: {
// purse: {
// totalSold: 12.99
// }
// }
// }
.forEach()
var productsSold = [
{
brand: 'Guchee',
total: '90.34',
tag: 'purse'
},
{
brand: 'Louie Veeton',
total: '12.99',
tag: 'purse'
},
{
brand: 'Guchee',
total: '5.34',
tag: 'belt'
},
{
brand: 'Tommy Heelfiger',
total: '34.66',
tag: 'watch'
},
{
brand: 'Mycol Coors',
total: '3.33',
tag: 'belt'
},
{
brand: 'Guchee',
total: '23.20',
tag: 'purse'
}
];
var categorizedProducts = {};
productsSold.forEach(function(product){
var brandName = snakeCase(product.brand); //
if(!categorizedProducts[brandName]) {
categorizedProducts[brandName] = {};
}
if(!categorizedProducts[brandName][product.tag]) {
categorizedProducts[brandName][product.tag] = {};
}
if(!categorizedProducts[brandName][product.tag].totalSold) {
categorizedProducts[brandName][product.tag].totalSold = 0;
}
categorizedProducts[brandName][product.tag].totalSold += parseFloat(product.total, 10);
});
function snakeCase(str){
str = str.replace(/\s/g, '_').toLowerCase();
return str;
}
.reduce()
var productsSold = [
{
brand: 'Guchee',
total: '90.34',
tag: 'purse'
},
{
brand: 'Louie Veeton',
total: '12.99',
tag: 'purse'
},
{
brand: 'Guchee',
total: '5.34',
tag: 'belt'
},
{
brand: 'Tommy Heelfiger',
total: '34.66',
tag: 'watch'
},
{
brand: 'Mycol Coors',
total: '3.33',
tag: 'belt'
},
{
brand: 'Guchee',
total: '23.20',
tag: 'purse'
}
];
var groomedObject = productsSold.reduce(function(obj, product){
var brandName = snakeCase(product.brand);
obj[brandName] = obj[brandName] || {};
obj[brandName][product.tag] = obj[brandName][product.tag] || {};
obj[brandName][product.tag].totalSold = obj[brandName][product.tag].totalSold || 0;
obj[brandName][product.tag].totalSold += parseFloat(product.total, 10);
return obj
}, {});
function snakeCase(str){
str = str.replace(/\s/g, '_').toLowerCase();
return str;
}
Do this