gpt4 book ai didi

javascript - 从嵌套的 JSON 数组中获取数据

转载 作者:行者123 更新时间:2023-11-30 14:53:10 25 4
gpt4 key购买 nike

我有一个这样的对象......

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;
});
});
}

这会返回原始的、未过滤的对象。

现在只是在兜圈子。任何指导将不胜感激!

最佳答案

您没有有效的对象。您将它包裹在 ""引号中,因此它是一个字符串。因此,您的过滤器将无法正常工作。您的对象中还有其他语法错误会阻止它正常工作。这是完整的修复:

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));

关于javascript - 从嵌套的 JSON 数组中获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47819820/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com