[英]unable to filter nested json object
我想根據GUI中的用戶輸入,使用procedureName
和hospitalName
過濾以下json數據。
myObject= [
{
"department": "Gynic",
"treatmentList": [
{
"procedureName": "Bone Grafting",
"hospitalList": [
{
"hospitalName": "Renai",
},
{
"hospitalName": "Aster",
},
{
"hospitalName": "Appolo",
}
],
},
{
"procedureName": "IVF",
"hospitalList": [
{
"hospitalName": "Renai",
}
],
}
]
}
]
例如,當使用程序名稱“ Bone Grafting”和醫院名稱“ Renai”過濾上述json時,我應以以下格式獲取結果。
[
{
"department": "Gynic",
"treatmentList": [
{
"procedureName": "Bone Grafting",
"hospitalList": [
{
"hospitalName": "Renai",
},
{
"hospitalName": "Aster",
},
{
"hospitalName": "Appolo",
}
],
}
]
}
]
我嘗試使用下面的代碼,但它沒有過濾json
var x = myObject.filter(function (obj) {
return obj.treatmentList.some(function (item) {
return item.procedureName == 'Bone Grafting';
});
});
有人可以幫助我糾正代碼中的錯誤嗎?
myObject
數組。 hospitalList
數組添加some
函數的新調用,並與hospitalName
屬性進行比較。 treatmentList
數組中。 var myObject = [{ "department": "Gynic", "treatmentList": [{ "procedureName": "Bone Grafting", "hospitalList": [{ "hospitalName": "Renai", }, { "hospitalName": "Aster", }, { "hospitalName": "Appolo", } ], }, { "procedureName": "IVF", "hospitalList": [{ "hospitalName": "Renai", }], } ] }]; var myResultObject = []; for (var i = 0; i < myObject.length; i++) { myResultObject.push({ 'department': myObject[i].department, 'treatmentList': myObject[i].treatmentList.filter(function(obj) { return obj.procedureName === 'Bone Grafting' && obj.hospitalList.some(function(hn) { return hn.hospitalName === 'Renai'; }); }) }); } console.log(myResultObject);
不知道這是否是最好的方法,但是您可以嘗試類似
var myObject = [{ "department": "Gynic", "treatmentList": [{ "procedureName": "Bone Grafting", "hospitalList": [{ "hospitalName": "Renai", }, { "hospitalName": "Aster", }, { "hospitalName": "Appolo", }], }, { "procedureName": "IVF", "hospitalList": [{ "hospitalName": "Renai", }], }] }]; function search(procedureName, hospitalName) { return myObject[0].treatmentList.filter(e => { if (e.procedureName === procedureName) { return e.hospitalList.filter(h => { return h.hospitalName === hospitalName }) } }) } console.log(search("IVF", "Renai"))
Array.some
只需要數組中的至少一個元素即可通過測試。 因此,filter方法返回true
,而不過濾任何內容。
以下方法可以滿足您的需求。
var x = myObject.map(function (obj) {
obj.treatmentList = obj.treatmentList.filter(function (item) {
return item.procedureName == 'Bone Grafting' &&
item.hospitalList.some(function (hospital) {
return hospital.hospitalName == 'Renai';
});
});
return obj;
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.