I have been experimenting with filtering a nested JSON array using Knockout js. Let me share how my JSON data is structured:
{
"groups": [{
"name": "Category1",
"items": [{
"question": "Question1",
"answer": "Answer1"
}]
}, {
"name": "Category2",
"items": [{
"question": "Question2",
"answer": "Answer2"
}, {
"question": "Question3",
"answer": "Answer3"
}]
}]
}
The goal here is to filter based on the "answer" field. This is how my current HTML page is formatted:
<div >
<div class="groups" data-bind="{foreach: {data: filteredGroups, as: 'group'}}">
<div class="name-row" data-bind="text: group.name"></div>
<div class="items" data-bind="{foreach: {data: group.items, as: 'item'}}">
<div class="item-row">
<div class="question-row">
<div class="question-content">
<div class="letter">Question</div>
<div data-bind="text: item.question"></div>
</div>
<div class="notch"> </div>
</div>
<div class="answer-row">
<div class="letter">Answer</div>
<div data-bind="text: item.answer"></div>
</div>
</div>
</div>
</div>
Below you will find the logic that I am currently implementing:
self.filteredGroups = ko.computed(function() {
if (!self.query()) {
return self.groups();
}
else {
var matchCount = 0;
return ko.utils.arrayFilter(self.groups(), function(group) {
return ko.utils.arrayFilter(group.items, function(item) {
//console.log("Entered==>" + self.query().toLowerCase() + " " + "Search==>" + item.question.toLowerCase());
var found = item.answer.toLowerCase().indexOf(self.query().toLowerCase());
if(found >= 0){
console.log("Number of occurrences" +matchCount++);
return true;
}else{
return false;
}
});
});
}
});
However, I seem to be facing issues when trying to execute this logic as it does not provide the desired filtered results. Can anyone help identify what might be missing in my approach?