我有一个json数组。从那里我想将重复的发票号记录推送到node.js中的另一个json数组。 我有json数组:
jarray:[{
"invoice": "C1"
"name": "Amit"
},
{"invoice": "C1"
"name": "Anish"
},
{
"code": "C2"
"name": "Anuj"
},
{
"code": "C3"
"name": "Sumit"
}
]
我想要的新json数组:
jarray1:[{
"invoice": "C1"
"name": "Amit"
},
{"invoice": "C1"
"name": "Anish"
}]
我如何在node.js中执行此操作?
答案 0 :(得分:1)
您可以使用underscore
或lodash
执行此操作,使用npm install
可以使用var _ = require('lodash');
var original = [
{
"invoice": "C1",
"name": "Amit"
},
{
"invoice": "C1",
"name": "Anish"
},
{
"invoice": "C2",
"name": "Anuj"
},
{
"invoice": "C3",
"name": "Sumit"
}
];
var grouped = _.countBy(original, function (item) {
return item.invoice
});
var duplicateInvoiceIds = [];
_.filter(grouped, function (qty, key) {
if (qty > 1) duplicateInvoiceIds.push(key);
});
var result = _.filter(original, function (item) {
return _.indexOf(duplicateInvoiceIds, item.invoice) > -1;
});
console.log(result);
获取这两者,并且这两者都可以使用以下代码:< / p>
{ C1: 2, C2: 1, C3: 1 }
这是一个3步骤的过程(为了清楚起见)。请注意,我假设原始数据应该始终显示“发票”,而不是在中途切换到“代码”。如果没有,请重新输入“代码”,然后默默跳过这些代码。
[ 'C1' ]
)。[ { invoice: 'C1', name: 'Amit' },
{ invoice: 'C1', name: 'Anish' } ]
)。这导致:
{{1}}