我想找到具有某些属性的对象。但是我有一个错误: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');
答案 0 :(得分: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; }
答案 1 :(得分:0)
采用对象的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'));