Within my code, I am dealing with an array of objects that contain sub-objects. This particular array is utilized in an ng-repeat to display data in a table format. To illustrate, consider the following example:
device {
"name": "computer"
ip_addresses {
"address" : "127.0.0.1",
"network" : "internet"
}
components {
"type" : "network interface",
"serial" : "12345"
}
}
I've developed a filter that simplifies the object into a string and scans the entire string for the specified query (enabling searches within both the outer and inner objects).
Although the filter functions correctly, I continuously encounter digest errors. My initial attempt involved removing unwanted objects from the array using splice, but this caused the filter to permanently take effect (meaning once an object was filtered out, it was removed indefinitely).
return function (input, filterStr) {
for (var i = 0; i < input.length; i++) {
if (JSON.stringify(input[i]).toUpperCase().indexOf(filterStr.toUpperCase()) == -1)
{
input.splice(i, 1);
}
}
return input;
}
An alternative method I experimented with was creating a new array and adding matching elements to it. However, this approach resulted in AngularJS recognizing the output array objects as distinct from those in the input array, triggering digest errors.
return function( items, filterStr) {
var filtered = [];
angular.forEach(items, function(item) {
if (JSON.stringify(item).toUpperCase().indexOf(filterStr.toUpperCase()) != -1)
{
filtered.push(item);
}
});
return filtered;
};
Therefore, my inquiry pertains to finding a solution to generate a filtered output array without altering the original array or causing digest errors by creating a completely new array. How can one create a filtered array safely and efficiently?