我有一个长度为 10000 的对象数组。我想操作数据。谁能帮我。
这就是我的数据的样子
[
{
"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"
}
]
这就是我想要操纵的方式。
[
{
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"
}
]
}
]
我想按文章类型和品牌
进行分组。谁能帮助我。
谢谢
最佳答案
您可以使用_.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>
关于javascript - 如何使用 underscore.js 对多个项目进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34429867/