我想用procedureName
&过滤下面的json数据。 hospitalName
基于GUI中的用户输入。
myObject= [
{
"department": "Gynic",
"treatmentList": [
{
"procedureName": "Bone Grafting",
"hospitalList": [
{
"hospitalName": "Renai",
},
{
"hospitalName": "Aster",
},
{
"hospitalName": "Appolo",
}
],
},
{
"procedureName": "IVF",
"hospitalList": [
{
"hospitalName": "Renai",
}
],
}
]
}
]
例如,当用程序名称'骨移植'过滤上述json时。 &安培;医院名称' Renai'我应该得到以下格式的结果。
[
{
"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';
});
});
有人可以帮我纠正我的代码中的错误吗?
答案 0 :(得分:1)
myObject
阵列。some
数组添加hospitalList
函数的新调用,并与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);
&#13;
答案 1 :(得分:0)
不确定这是否是最好的方法,但你可以试试
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"))
&#13;
答案 2 :(得分:0)
Array.some
只需要数组中至少有一个元素通过测试。因此,过滤方法返回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;
});