Reputation: 7601
I have an array for a table:
groupTable: {
data: {
head: ['name', 'user', 'date'],
body: [{
name: 'Group 1',
user: 'User 3',
date: '17/10/03'
}, {
name: 'Group 2',
user: 'User 2',
date: '16/10/01'
}]
}
}
I want to be able to filter the objects inside groupTable.data.body
. I did this:
// let's say the term is "7"
const result = this.groupTable.data.body.filter(field => {
return Object.values(field).every(value => {
return value.indexOf(term) > -1
});
});
console.log(result)
In this case, console.log(result)
should return (if term
= "7"
):
[{
name: 'Group 1',
user: 'User 3',
date: '17/10/03'
}]
However, I get an empty array. Why is this and how to fix it?
Upvotes: 0
Views: 745
Reputation: 1242
So as I mentioned above, don't use ".every" since that means it needs all your field's values to meet that criteria. Instead use ".some". That way it'll return "true" for any of the fields that have that "term" you stated. The Javascript function is really readable if you just say it out: "I want to FILTER down the data where SOME values contain the provided term". I'm thinking that's what you want not: "I want to FILTER down the data where EVERY value contain the provided term"
// let's say the term is "7"
const result = this.groupTable.data.body.filter(field => {
return Object.values(field).some(value => {
return value.indexOf(term) > -1
});
});
console.log(result)
Upvotes: 1