I am trying to filter an array with a text match with many elements. But my implementation only uses the first element to filter the array.
dataSource =
dataSource &&
dataSource.itemList.filter((result: any) =>
(
result.lotNumber ||
result.year ||
result.make ||
result.model ||
result.stockNumber ||
result.vin ||
result.mileageType ||
result.intColor ||
result.engine ||
result.crGrade ||
result.transmission ||
result.sellerName
)
.toLowerCase()
.includes(searchedText.toLowerCase())
);
In my solution, it only works for result.lotNumber
. What seems to be the issue here?
Concat the values and do not use boolean operators.
dataSource =
dataSource &&
dataSource.itemList.filter((result: any) =>
(
'' +
result.lotNumber + ' ' +
result.year + ' ' +
result.make + ' ' +
result.model + ' ' +
result.stockNumber + ' ' +
result.vin + ' ' +
result.mileageType + ' ' +
result.intColor + ' ' +
result.engine + ' ' +
result.crGrade + ' ' +
result.transmission + ' ' +
result.sellerName
)
.toLowerCase()
.includes(searchedText.toLowerCase())
);
By using ||
, the search is based on the first value not falsy.
You can add spaces to prevent that the concatenated values will match something by error.
Example:
If
result.model = 'V' and
result.stockNumber = '2'
By looking for 'V2', you'll have a match although it shouldn't. By adding spaces, you prevent that.
Enhancing the answer from sjahan , you can itterate the object keys of result
without adding them one by one manually:
dataSource =
dataSource &&
dataSource.itemList.filter((result: any) =>
(Object.keys(result).map(key => result[key])).join(' ')
.toLowerCase()
.includes(searchedText.toLowerCase())
);
const itemList = [{ lotNumber: '123', year: '2020', make: 'doe', model: 'model', }, { lotNumber: '456', year: '2019', make: 'jane', model: 'othermodel', }]; const result = (search) => itemList.filter((result) => (Object.keys(result).map(key => result[key])).join(' ') .toLowerCase() .includes(search.toLowerCase()) ); console.log(result('123')); console.log(result('jane'));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.