Assume this object:
const data = {
"text-a": ["Text-1", "Text-2", "Example-3", "Text-4"],
"text-b": ["Example-1", "Example-2", "Other-Example-3", "Text-1b"]
}
// This object should be updated only with the data that matches the searchInput.
var filteredData = {}
// This value changes on user text input.
var searchInput = "tex"
and need to filter it based on user text input. The filter should be applied to the array values, and when no values match the search input, remove its key as well.
my current non-working implementation looks like this, but I cannot get it working as it returns always ‘undefined:
filteredData = Object.keys(data).forEach((key) => (
filteredData[key] = data[key].filter((x) =>
(x.includes(searchInput)))
))
thank you.
3
Answers
Three remarks about your code:
includes
performs a case-sensitive search, my suggestion uses a case-insensitive regular expression.filteredData
you construct is an array, but you seem to want an object.Try this code:
and if you want make case insensitive:
The
.forEach()
method returnsundefined
in JavaScript, so assigning the result of that tofilteredData
is going to makefilteredData
undefined.One way to approach this is to get the entries of your
data
object ([[key, value], [key2, value2], ...]
and then map each of the inner entry arrays (using.map()
) to new entries, where each value is a filtered version of your array. Once you’ve transformed each inner entry array by mapping it, you can perform an additional filter to keep only the key-value pairs where your array’s value length is more than0
(non-empty). You can then convert the transformed array of entries into a new object usingObject.fromEntries()
: