JSON中可以有相同的值" treaty_number",并且可以有很多。
*.mysite.com
如何按相同的值对它们进行分组?我在角度2上写,但它有可能和纯粹的JS。 (我知道有一个lodash库,但无法过滤数据)。
结论:
[
{
"id": 1,
"treaty_number": "as32dd",
"name": "Name1",
"company": "Company1",
"beneficiary": "beneficiary1",
},
{
"id": 2,
"treaty_number": "cgs22t2",
"name": "Name2",
"company": "Company2",
"beneficiary": "beneficiary2",
},
{
"id": 3,
"treaty_number": "as32dd",
"name": "Name3",
"company": "Company3",
"beneficiary": "beneficiary3",
},
{
"id": 4,
"treaty_number": "ff2153",
"name": "Name4",
"company": "Company4",
"beneficiary": "beneficiary4",
},
{
"id": 5,
"treaty_number": "as32dd",
"name": "Name5",
"company": "Company5",
"beneficiary": "beneficiary5",
},
{
"id": 6,
"treaty_number": "cgs22t2",
"name": "Name6",
"company": "Company6",
"beneficiary": "beneficiary6",
},
{
"id": 7,
"treaty_number": "hg2545s",
"name": "Name7",
"company": "Company7",
"beneficiary": "beneficiary7",
},
etc..
]
然后对于每个组,它将显示在自己的表中。
还有问题,如何正确演绎呢?毕竟,如果对于每个组(并且可能有许多组)将有一个数组,如何处理视图中的数据并逐个显示在表中?
[
{
"id": 1,
"treaty_number": "as32dd",
"name": "Name1",
"company": "Company1",
"beneficiary": "beneficiary1",
},
{
"id": 3,
"treaty_number": "as32dd",
"name": "Name3",
"company": "Company3",
"beneficiary": "beneficiary3",
},
{
"id": 5,
"treaty_number": "as32dd",
"name": "Name5",
"company": "Company5",
"beneficiary": "beneficiary5",
}
];
[
{
"id": 2,
"treaty_number": "cgs22t2",
"name": "Name2",
"company": "Company2",
"beneficiary": "beneficiary2",
},
{
"id": 6,
"treaty_number": "cgs22t2",
"name": "Name6",
"company": "Company6",
"beneficiary": "beneficiary6",
}
]
答案 0 :(得分:0)
如果您的工作流程允许您使用es6功能(例如,您使用Babel来转换源文件),我会使用Set
数据结构。请参阅documentation。
答案 1 :(得分:0)
您可以使用underscore
或lodash
each
功能和groupby
功能来实现所需的输出。
var data = [{
"id": 1,
"treaty_number": "as32dd",
"name": "Name1",
"company": "Company1",
"beneficiary": "beneficiary1",
},
{
"id": 2,
"treaty_number": "cgs22t2",
"name": "Name2",
"company": "Company2",
"beneficiary": "beneficiary2",
},
{
"id": 3,
"treaty_number": "as32dd",
"name": "Name3",
"company": "Company3",
"beneficiary": "beneficiary3",
},
{
"id": 4,
"treaty_number": "ff2153",
"name": "Name4",
"company": "Company4",
"beneficiary": "beneficiary4",
},
{
"id": 5,
"treaty_number": "as32dd",
"name": "Name5",
"company": "Company5",
"beneficiary": "beneficiary5",
},
{
"id": 6,
"treaty_number": "cgs22t2",
"name": "Name6",
"company": "Company6",
"beneficiary": "beneficiary6",
},
{
"id": 7,
"treaty_number": "hg2545s",
"name": "Name7",
"company": "Company7",
"beneficiary": "beneficiary7",
}
]
var result = [];
_.each(_.groupBy(data, function(obj) {
return obj.treaty_number
}), function(i) {
result.push(i);
});
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore.js"></script>