javascript - Filtering in nested array -
i have nested data structure mapped array in knockout js:
class departments{ string departmentname; list<group> groups } class group{ string groupname; list<person> persons; } class person{ string firsname; string lastname; }
i fetched data server , show them in ui successfully. want convert array computed 1 in knockoutjs , filter firstname
, lastname
. it's worthy mention have bound self.search_firstname , self.search_lastname
2 different inputs. html code binding data follow:
<div class="form-group"> <input type="text" class="text-right text-success input-lg" placeholder="name" data-bind="value:search_firstname, valueupdate: 'afterkeydown'" /> </div> <div class="panel-group" id="accordion" data-bind="foreach: profiles" role="tablist" aria-multiselectable="true"> <div class="panel panel-default"> <div class="panel-heading"> <h4 class="panel-title" data-bind="text: departmentname"></h4> </div> <div class="panel-collapse collapse in"> <div class="panel-body"> <table data-bind="foreach: { data: groupvms }" class="table table-responsive col-lg-12 col-sm-12 col-md-12"> <tbody> <tr><td class="groups" data-bind="text: groupname"></td></tr> <tr> <td> <table data-bind="foreach: { data: personphonesvms }" class="table table-striped table-responsive col-lg-12 col-sm-12 col-md-12"> <tr> <td class="col-lg-1 col-sm-1 col-md-1" data-bind="text: prefix"></td> <td class="col-lg-2 col-sm-2 col-md-2" data-bind="text: firstname"></td> <td class="col-lg-3 col-sm-3 col-md-3" data-bind="text: lastname"></td> </tr> </table> </td> </tr> </tbody> </table> </div> </div> </div> </div>
now want during typing in text box search_firstname
data automatically filtered. right can filter records based on departmentname
following code:
self.profiles = ko.computed(function () { return ko.utils.arrayfilter(self.backupprofiles(), function (rec) { return ( (self.search_firstname().length == 0 || rec.departmentname.indexof(self.search_firstname()) > -1) ); }); });
does has idea filtering records based on firstname , lastname fields?
i have created a fiddle you. computed
@ heart of builds structure profiles structure, including matched records.
vm.filteredprofiles = ko.computed(function () { var first = vm.search_firstname().tolocalelowercase(); if (first === '') return vm.profiles(); var result = []; ko.utils.arrayforeach(vm.profiles(), function (dept) { var groupsmatched = []; ko.utils.arrayforeach(dept.groupvms(), function (group) { var personsmatched = []; ko.utils.arrayforeach(group.personphonesvms(), function (person) { if (person.firstname().tolocalelowercase().indexof(first) > -1) { personsmatched.push(person); } }); if (personsmatched.length > 0) { groupsmatched.push({ groupname: group.groupname, personphonesvms: personsmatched }); } }); if (groupsmatched.length > 0) { result.push({ departmentname: dept.departmentname, groupvms: groupsmatched }); } }); return result; });
Comments
Post a Comment