【问题标题】:TypeError: obj[key].includes is not a function: in filter functionTypeError: obj[key].includes 不是函数:在过滤器函数中
【发布时间】:2019-09-23 14:59:56
【问题描述】:
我想找到具有某种价值的任何属性的对象。但我有错误:TypeError: obj[key].includes is not a function。
如何解决?
var aa = [{id: 1,type: 1,status: 1,name: 'txt'},{id: 2,type: 1,status: 1,name: 'txt'},{id: 3,type: 0,status: 0,name: 'txt'}];
function filterIt(arr, searchKey) {
return arr.filter(function(obj) {
return Object.keys(obj).some(function(key) {
return obj[key].includes(searchKey);
})
});
}
filterIt(aa, 'txt');
【问题讨论】:
标签:
javascript
arrays
object
ecmascript-6
filter
【解决方案1】:
尝试改用Object.values:
var aa = [{id: 1,type: 1,status: 1,name: 'txt'},{id: 2,type: 1,status: 1,name: 'txt'},{id: 3,type: 0,status: 0,name: 'txt'}];
function filterIt(arr, searchKey) {
return arr.filter(function(obj) {
return Object.values(obj).includes(searchKey);
});
}
console.log(filterIt(aa, 'txt'));
.as-console-wrapper { max-height: 100% !important; top: auto; }
您还可以使这段代码更紧凑:
var aa = [{id: 1,type: 1,status: 1,name: 'txt'},{id: 2,type: 1,status: 1,name: 'txt'},{id: 3,type: 0,status: 0,name: 'txt'}];
const filterIt = (arr, searchKey) => arr.filter(obj => Object.values(obj).includes(searchKey));
console.log(filterIt(aa, 'txt'));
.as-console-wrapper { max-height: 100% !important; top: auto; }
【解决方案2】:
取对象的Object.values 得到一个值数组,然后你可以查看是否有任何值与searchKey 匹配(不过,你正在搜索values,所以可能最好把它命名为valueToFind):
var aa = [{
id: 1,
type: 1,
status: 1,
name: 'txt'
},
{
id: 2,
type: 1,
status: 1,
name: 'txt',
},
{
id: 3,
type: 0,
status: 0,
name: 'txt'
},
{
id: 4,
type: 0,
status: 0,
name: 'wrongname'
},
];
function filterIt(arr, valueToFind) {
return arr.filter(function(obj) {
return Object.values(obj).includes(valueToFind);
});
}
console.log(filterIt(aa, 'txt'));
因为您使用的是.some,请考虑使用 ES6 语法以获得更简洁的代码:
var aa = [{
id: 1,
type: 1,
status: 1,
name: 'txt'
},
{
id: 2,
type: 1,
status: 1,
name: 'txt',
},
{
id: 3,
type: 0,
status: 0,
name: 'txt'
},
{
id: 4,
type: 0,
status: 0,
name: 'wrongname'
},
];
const filterIt = (arr, valueToFind) => arr.filter(
obj => Object.values(obj).includes(valueToFind)
);
console.log(filterIt(aa, 'txt'));