Reputation: 511
I would like find objects that have any propery with some value. But I have error: TypeError: obj[key].includes is not a function. How to fix it?
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');
Upvotes: 0
Views: 1179
Reputation: 44125
Try using Object.values
instead:
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; }
You can also make this code more compact:
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; }
Upvotes: 1
Reputation: 370979
Take the Object.values
of the object to get an array of values, and then you can see if any values match the searchKey
(though, you're searching for values, so probably better to name it 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'));
Because you were using .some
, consider using ES6 syntax for more concise code:
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'));
Upvotes: 0