gpt4 book ai didi

javascript - 对 JSON 数据中的值进行深度过滤

转载 作者:行者123 更新时间:2023-11-27 22:50:09 24 4
gpt4 key购买 nike

我有一些 JSON 数据,我试图根据 JavaScript 中用户的复选框选择来过滤这些数据,但我在多级过滤方面遇到了障碍。我有两个维度的数据需要从 JSON 中过滤;首先根据操作系统选择过滤 JSON 数据,然后使用选定的问题过滤器过滤生成的操作系统选择数据。例如,我正在执行以下操作:

$('.os-checkbox input[type="checkbox"]:checked').each(function() {
OSSelected.push(Number($(this).parents('.checkbox').index()));
});

$('.question-checkbox input[type="checkbox"]:checked').each(function() {
QuestionSelected.push(Number($(this).parents('.checkbox').index()));
});

var array = $scope.data.responses;
var osSelectionFilter = array.filter(function(elem, index) {
return (JSON.stringify(elem.OSSelectedIndex) == JSON.stringify(OSSelected));
});

console.log(osSelectionFilter); // should return all 'data.response.OSSelectedIndex' objects with the selection made, ex. 0-PC so any selection with "OSSelectedIndex": [0] included

var questionSelectionFilter = osSelectionFilter.filter(function(elem, index) {
return (JSON.stringify(elem.questionSelectedIndex) == JSON.stringify(QuestionSelected));
});

console.log(questionSelectionFilter); // should filter the osSelectionFilter above and return all objects with the questions array included, ex. 0, 1, 2...

过滤选择后,JSON 中的“结果”数据将填充 div。现在的问题是过滤器正在尝试过滤我猜测的整个数组,例如查找 [0, 1],而不是单独查找数组中的每个值;其中值 [0] 和 [1] 是两个不同的单独选择。

来自 CMS 的 JSON 数据如下所示:

{
"id": "test1",
"fields": {
"OS": [
"PC",
"Mac",
"Android",
"iOS"
],
"questions": [{
"question": "Question 0"
}, {
"question": "Question 1"
}, {
"question": "Question 2"
}, {
"question": "Question 3"
}, {
"question": "Question 4"
}, {
"question": "Question 5"
}, {
"question": "Question 6"
}],
"responses": [{
"ID": 1,
"OSSelectedIndex": [ 0 ],
"questionSelectedIndex": [],
"result": "<h1>Response 1 found</h1>"
}, {
"ID": 2,
"OSSelectedIndex": [ 0, 1 ],
"questionSelectedIndex": [ 0, 1, 2 ],
"result": "<h1>Response 2 found</h1>"
}, {
"ID": 3,
"OSSelectedIndex": [ 0, 2 ],
"questionSelectedIndex": [ 0, 1, 2, 5 ],
"result": "<h1>Response 3 found</h1>"
}, {
"ID": 4,
"OSSelectedIndex": [ 1, 2 ],
"questionSelectedIndex": [ 1, 2, 3, 4 ],
"result": "<h1>Response 4 found</h1>"
}]
}
}

这样的设置可能吗?

使用上述代码的 Plunker:

https://plnkr.co/edit/N1NJKDOgvVkB9gPmPooi?p=preview

非常感谢

最佳答案

尝试将过滤器更改为:

var osSelectionFilter = array.filter(function(elem, index) {
for(var i = 0; i < elem.OSSelectedIndex.length; i++) {
if(OSSelected.indexOf(elem.OSSelectedIndex[i]) >= 0) {
return true;
}
}
return false;
});

...

var questionSelectionFilter = osSelectionFilter.filter(function(elem, index) {
for(var i = 0; i < elem.questionSelectedIndex.length; i++) {
if(QuestionSelected.indexOf(elem.questionSelectedIndex[i]) >= 0) {
return true;
}
}
return false;
});

已更新plnkr

关于javascript - 对 JSON 数据中的值进行深度过滤,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38122962/

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