Reputation: 219
I have an array of objects with length 10000. I want to manipulate the data. can anyone help me.
This is how, my data looks like
[
{
"date": "Nov 24, 2015",
"article_type": "Casual Shoes",
"brand": "Puma",
"realised_revenue": "596,882.3",
"realised_quantity": "289"
},
{
"date": "Nov 23, 2015",
"article_type": "Casual Shoes",
"brand": "Puma",
"realised_revenue": "595,882.3",
"realised_quantity": "288"
},
{
"article_type": "Sports Shoes",
"brand": "Puma",
"date": "Nov 23, 2015",
"realised_revenue": "394,195.9",
"realised_quantity": "134"
},
{
"article_type": "Sweatshirts",
"brand": "Puma",
"date": "Nov 23, 2015",
"realised_revenue": "337,385.2",
"realised_quantity": "191"
}
]
This is how, I want to manipulate.
[
{
groupByRes:{"article_type": "Casual Shoes","brand": "Puma"},
results:[
{
"date": "Nov 24, 2015",
"article_type": "Casual Shoes",
"brand": "Puma",
"realised_revenue": "596,882.3",
"realised_quantity": "289"
},
{
"date": "Nov 23, 2015",
"article_type": "Casual Shoes",
"brand": "Puma",
"realised_revenue": "595,882.3",
"realised_quantity": "288"
}
]
},
{
groupByRes:{"article_type": "Sports Shoes","brand": "Puma"},
results:[
{
"article_type": "Sports Shoes",
"brand": "Puma",
"date": "Nov 23, 2015",
"realised_revenue": "394,195.9",
"realised_quantity": "134"
}
]
},
{
groupByRes:{"article_type": "Sweatshirts,"brand": "Puma"},
results:[
{
"article_type": "Sweatshirts",
"brand": "Puma",
"date": "Nov 23, 2015",
"realised_revenue": "337,385.2",
"realised_quantity": "191"
}
]
}
]
I want to group by article_type and brand
. can anyone help me.
Thanks
Upvotes: 0
Views: 27
Reputation: 13692
You can "cheat" by using _.groupBy()
:
var arr = [
{
"date": "Nov 24, 2015",
"article_type": "Casual Shoes",
"brand": "Puma",
"realised_revenue": "596,882.3",
"realised_quantity": "289"
},
{
"date": "Nov 23, 2015",
"article_type": "Casual Shoes",
"brand": "Puma",
"realised_revenue": "595,882.3",
"realised_quantity": "288"
},
{
"date": "Nov 23, 2015",
"article_type": "Casual Shoes",
"brand": "Not Puma",
"realised_revenue": "595,882.3",
"realised_quantity": "288"
},
{
"article_type": "Sports Shoes",
"brand": "Puma",
"date": "Nov 23, 2015",
"realised_revenue": "394,195.9",
"realised_quantity": "134"
},
{
"article_type": "Sweatshirts",
"brand": "Puma",
"date": "Nov 23, 2015",
"realised_revenue": "337,385.2",
"realised_quantity": "191"
}
];
var out = _(arr).groupBy(function (obj) {
// return a stringified object containing the type and the brand
return JSON.stringify({ "article_type": obj.article_type, "brand": obj.brand });
}).map(function(value, key) {
return {
// parse back the key which is a stringified object
groupByRes: JSON.parse(key),
results: value
}
}).value();
out = JSON.stringify(out, null, 3);
console.log(out);
document.write('<pre>' + out + '</pre>');
<script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.1/lodash.js'></script>
Upvotes: 2