Reputation: 4885
i'm trying to filter an array of objects based on them objects having a value which partially matches a string.
const acceptedValues = "theme";
const myObject = {
code: "themev3",
}
var filteredObject = Object.keys(myObject).reduce(function(r, e) {
if (acceptedValues.indexOf(myObject[e].toLowerCase()) >= 0) r[e] = myObject[e]
return r;
}, {})
console.log(filteredObject);
As you can see the object above should be returned in the filteredObject
array as code
has got theme
in it.
This is not working however, any ideas why?
Upvotes: 0
Views: 45
Reputation: 386550
Beside the switching comparison, you could map the key/value pairs and build new objects after filtering.
const
value = "theme",
object = { code: "themev3" },
filtered = Object.assign(
...Object
.entries(object)
.filter(([, v]) => v.toLowerCase().includes(value))
.map(([key, value]) => ({ [key]: value }))
);
console.log(filtered);
Upvotes: 1
Reputation: 23859
The condition should be reverse. You need to find the index of acceptedValues
in the object values instead:
const acceptedValues = "theme";
const myObject = {
code: "themev3",
}
var filteredObject = Object.keys(myObject).reduce(function(r, e) {
if (myObject[e].toLowerCase().indexOf(acceptedValues.toLowerCase()) > -1)
r[e] = myObject[e];
return r;
}, {})
console.log(filteredObject);
Upvotes: 0
Reputation: 28445
You are mixing up the searched text and search from text. Over here you need to check whether myObject[e]
has any part of the acceptedValues
const acceptedValues = "theme";
const myObject = {
code: "themev3",
}
var filteredObject = Object.keys(myObject).reduce(function(r, e) {
if (myObject[e].toLowerCase().indexOf(acceptedValues) >= 0) r[e] = myObject[e]
return r;
}, {})
console.log(filteredObject);
Also, you can use includes
in place of indexOf
like following
if(myObject[e].toLowerCase().includes(acceptedValues))
Upvotes: 1