我想找到具有某种值(value)的任何属性的对象。但我有错误: TypeError: obj[key].includes 不是函数。 如何解决?
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');
最佳答案
尝试使用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; }
关于javascript - TypeError : obj[key]. 包括不是一个函数:在过滤器函数中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55997331/