I wanted to filter the values in an array of objects by a certain value. When I run the function, I get TypeError: obj[key].includes is not a function
. I am using reactjs. What I'm I missing in the function?
var arr = [{
name: 'xyz',
grade: 'x'
}, {
name: 'yaya',
grade: 'x'
}, {
name: 'x',
frade: 'd'
}, {
name: 'a',
grade: 'b'
}];
filterIt(arr, searchKey) {
return arr.filter(obj => Object.keys(obj)
.map(key => obj[key].includes(searchKey)));
}
I got this example from and tried it out
I wanted to filter the values in an array of objects by a certain value. When I run the function, I get TypeError: obj[key].includes is not a function
. I am using reactjs. What I'm I missing in the function?
var arr = [{
name: 'xyz',
grade: 'x'
}, {
name: 'yaya',
grade: 'x'
}, {
name: 'x',
frade: 'd'
}, {
name: 'a',
grade: 'b'
}];
filterIt(arr, searchKey) {
return arr.filter(obj => Object.keys(obj)
.map(key => obj[key].includes(searchKey)));
}
I got this example from https://stackoverflow./a/40890687/5256509 and tried it out
Share Improve this question edited May 23, 2017 at 12:13 CommunityBot 11 silver badge asked Jan 12, 2017 at 16:23 HanmaslahHanmaslah 7461 gold badge8 silver badges14 bronze badges 14-
so what is
obj[key]
? Sounds like it is not what you think it is. – epascarello Commented Jan 12, 2017 at 16:25 -
What's
obj
? Are all of the properties of it objects with anincludes
method? – Heretic Monkey Commented Jan 12, 2017 at 16:25 -
obj[key]
is the value of thekey
passed @epascarello – Hanmaslah Commented Jan 12, 2017 at 16:28 - What is it when it fails.... Not seeing an the array/objects your question is basically impossible to answer. – epascarello Commented Jan 12, 2017 at 16:29
- @epascarello I have updated the question – Hanmaslah Commented Jan 12, 2017 at 16:32
1 Answer
Reset to default 3You can't filter array of object like this, because this bination
Object.keys(obj).map(key => obj[key].includes(searchKey))
always provides an array (with true
and false
values), and any array is truthy. Hence filter doesn't filter anything. You can try something like this:
arr.filter(obj =>
Object.keys(obj)
.some(key => obj[key].includes(searchKey))
);