TypeError:obj [key] .includes在过滤数组中对象的值时不是函数

时间:2017-01-12 16:23:37

标签: javascript ecmascript-6 filtering

我想按特定值过滤对象数组中的值。当我运行该函数时,我得到TypeError: obj[key].includes is not a function。我正在使用reactjs。我在功能中缺少什么?

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

我从https://stackoverflow.com/a/40890687/5256509得到了这个例子并尝试了

1 个答案:

答案 0 :(得分:2)

你不能像这样过滤对象数组,因为这个组合

Object.keys(obj).map(key => obj[key].includes(searchKey))

总是提供一个数组(truefalse值),任何数组都是真的。因此过滤器不会过滤任何东西。你可以尝试这样的事情:

arr.filter(obj => 
   Object.keys(obj)
     .some(key => obj[key].includes(searchKey))
);