javascript - TypeError: obj[key].includes is not a function when filtering values of an object in an array - Stack Overflow

I wanted to filter the values in an array of objects by a certain value. When I run the function, I get

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 an includes method? – Heretic Monkey Commented Jan 12, 2017 at 16:25
  • obj[key] is the value of the key 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
 |  Show 9 more ments

1 Answer 1

Reset to default 3

You 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))
);

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745638298a4637530.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信