I am trying to compare whether a value exists via Array.prototype.includes() but it is not working as expected.
See below
async loadFilterCheckboxState() {
// If filterString = Cliente=6&Recrutador=45,37&Negociador=45,43,8
// Cliente and value 6 will be checked in the filterList.filters
// Recrutador and value 45,37 will be checked in the filterList.filters
// Negociador and value 45,43,8 will be checked in the filterList.filters
// return if filterString is empty or ?
if (this.filterString === "?" || this.filterString === "") {
console.log("filterString is empty");
return;
}
const _filterString = this.filterString;
const _filterList = this.filterList;
const _filterArray = _filterString.split("&");
_filterArray.forEach((filter) => {
const _filterName = filter.split("=")[0];
const _filterValue = filter.split("=")[1];
const _filterValueArray = _filterValue.split(",");
const _filterItem = _filterList.find((item) => item.name === _filterName);
_filterItem.filters.forEach((item) => {
console.log("SEARCHING: " _filterValueArray " IN " item.value);
if (_filterValueArray.includes(item.value)) {
item.checked = true;
console.log("Match: " item.checked);
} else {
console.log("Not Match");
}
});
});
}
CodePudding user response:
Without being able to see the data in _filterList
it's not possible to say for sure, but having played around with your code I suspect this will be a type mismatch. Array.includes()
will use strict equality to compare values and so if your _filterList
has numbers rather than strings, then you will need to do a type conversion before calling Array.includes()
.
Below is the code I tested with. As you can see, in cases where the value of a filter was a string the code found the match, and in cases where the value of a filter was a number it did not:
const _filterString = 'Cliente=6&Recrutador=45,37&Negociador=45,43,8';
const _filterList = [
{name: 'Cliente', filters: [{value: '6', checked: ''}]},
{name: 'Recrutador', filters: [{value: 45, checked: ''}]},
{name: 'Negociador', filters: [{value: '8', checked: ''}]}
];
const _filterArray = _filterString.split("&");
_filterArray.forEach((filter) => {
const _filterName = filter.split("=")[0];
const _filterValue = filter.split("=")[1];
const _filterValueArray = _filterValue.split(",");
const _filterItem = _filterList.find((item) => item.name === _filterName);
_filterItem.filters.forEach((item) => {
console.log("SEARCHING: " _filterValueArray " IN " item.value);
if (_filterValueArray.includes(item.value)) {
item.checked = true;
console.log("Match: " item.checked);
} else {
console.log("Not Match");
}
});
});
Results:
SEARCHING: 6 IN 6
Match: true
SEARCHING: 45,37 IN 45
Not Match
SEARCHING: 45,43,8 IN 8
Match: true