我有一个像这样的物体......
var oInfoModal = "{"modals":[{"myID":17,"warningIdx":[0]},{"myID":12,"warningIdx":[1,2]},{"myID":11,"warningIdx":[3]},{"myID":10,"warningIdx":[4]},{"myID":9,"warningIdx":[5,6,7]},{"myID":8,"warningIdx":[8]},{"myID":7,"warningIdx":[9,10]},{"myID":6,"warningIdx":[11,12]},{"myID":5,"warningIdx":[13,14]},{"myID":4,"warningIdx":[15,16]},{"myID":3,"warningIdx":[17]},{"myID":1,"warningIdx":[18,19]},{"myID":0,"warningIdx":[20,21]}]}";
我想根据传递给函数的warnIdx值过滤对象,但我得到的是空对象。我知道问题是oInfoModal.modals.warningIdx本身是一个数组。但我不确定如何返回已过滤的oInfoModal.modals对象。
function filterInfoModals(warnIdx) {
return oInfoModal.modals.filter(function (item) {
return item.warningIdx == warnIdx;
});
}
我也试过
function filterInfoModals(warnIdx) {
return oInfoModal.modals.filter(function (item) {
return item.warningIdx.filter(function (idx,val) {
return val.warningIdx == warnIdx;
});
});
}
这让我回到了未经过滤的原始物体。
现在就进入圈子。任何指导将不胜感激!
答案 0 :(得分:2)
您没有有效的对象。你把它包裹在" "引号,因此它是一个字符串。因此,您的过滤器无法正常工作。您的对象中还有其他语法错误会阻止它正常工作。这是完整的修复:
var oInfoModal = {
"modals": [
{ "myID": 17, "warningIdx": [0] },
{ "myID": 12, "warningIdx": [1, 2] },
{ "myID": 11, "warningIdx": [3] },
{ "myID": 10, "warningIdx": [4] },
{ "myID": 9, "warningIdx": [5, 6, 7] },
{ "myID": 8, "warningIdx": [8] },
{ "myID": 7, "warningIdx": [9, 10] },
{ "myID": 6, "warningIdx": [11, 12] },
{ "myID": 5, "warningIdx": [13, 14] },
{ "myID": 4, "warningIdx": [15, 16] },
{ "myID": 3, "warningIdx": [17] },
{ "myID": 1, "warningIdx": [18, 19] },
{ "myID": 0, "warningIdx": [20, 21] }
]
};
function filterInfoModals(warnIdx) {
return oInfoModal.modals.filter(function (item) {
return item.warningIdx.indexOf(warnIdx) > -1;
});
}
console.log(filterInfoModals(1,2));