我有一个JSON
数据对象,我从mongoDB
检索。它具有以下格式:
var billData = [{
"_id": "PT155/454",
"_class": "com.aventyn.hms.domain.OPDBill",
"billingDate": "2017-11-20",
"patientId": "PT155",
"transactions": [{
"txnId": "PT155/454/1",
"toBePaid": "0",
"txnAmount": "0",
"due": "0",
"selfPay": true
}, {
"txnId": "PT155/454/2",
"toBePaid": "450",
"txnAmount": "350",
"due": "100",
"selfPay": false
}]
}, {
"_id": "PT156/455",
"_class": "com.aventyn.hms.domain.OPDBill",
"billingDate": "2017-11-20",
"patientId": "PT156",
"transactions": [{
"txnId": "PT156/455/1",
"toBePaid": "300",
"txnAmount": "200",
"due": "100",
"selfPay": true
}, {
"txnId": "PT156/455/2",
"toBePaid": "100",
"txnAmount": "50",
"due": "50",
"selfPay": true
}]
}];
我的问题是我要删除那些具有selfPay: false
属性的事务,我正在执行以下操作,但它无法正常工作:
$.each(billData, function (k, v) {
$.each(v.transactions, function (tK, tV) {
if (tV.selfPay == true) {
billData[k].transactions = tV;
}
});
});
但是我获得的数据与我从数据库中获得的数据相同。
我知道如何实现这一目标?
感谢您的帮助。
jsfiddle的链接是:https://jsfiddle.net/0uy38pLf/
答案 0 :(得分:3)
您可以使用Array#map和Array#filter的组合来获得所需的结果(甚至不使用任何jQuery方法):
var billData = [{
"_id": "PT155/454",
"_class": "com.aventyn.hms.domain.OPDBill",
"billingDate": "2017-11-20",
"patientId": "PT155",
"transactions": [{
"txnId": "PT155/454/1",
"toBePaid": "0",
"txnAmount": "0",
"due": "0",
"selfPay": true
},
{
"txnId": "PT155/454/2",
"toBePaid": "450",
"txnAmount": "350",
"due": "100",
"selfPay": false
}
]
},
{
"_id": "PT156/455",
"_class": "com.aventyn.hms.domain.OPDBill",
"billingDate": "2017-11-20",
"patientId": "PT156",
"transactions": [{
"txnId": "PT156/455/1",
"toBePaid": "300",
"txnAmount": "200",
"due": "100",
"selfPay": true
},
{
"txnId": "PT156/455/2",
"toBePaid": "100",
"txnAmount": "50",
"due": "50",
"selfPay": true
}
]
}
];
var result = billData.map(bill => {
bill.transactions = bill.transactions.filter(tran => tran.selfPay);
return bill;
});
console.log(result);
答案 1 :(得分:1)
据我所知,它可能会更好,你否定了if子句。这样您就可以查看selfPay === false
。
console.log(billData);
$.each(billData,function(k,v){
$.each(v.transactions,function(tK,tV){
if(tV.selfPay === false ){
billData[k].transactions.splice(tK, 1);
}
});
});
console.log(billData)
另外我猜你想要删除那个单项。要删除单个项目,请使用splice
函数,该函数将获取您要删除的项目的索引tK
。
希望它有所帮助!