Given data in this format:
// projects.json
{
businessName: "",
address: "",
city: "",
reference: "",
contacts: [
{
name: ""
phone: ""
},
{
name: ""
phone: ""
}
],
}
... and a search function (btw, this is a Vue app) which iterates the 'project' objects of the json:
export default {
computed: {
filteredProjects: function() {
const searchTerm = this.search.toLowerCase();
if (!searchTerm) {
return false;
}
return this.projects.filter((project) => {
return (project.businessName.toLowerCase().match(searchTerm)) ||
(project.reference.toLowerCase().match(searchTerm));
});
}
} // computed
} // export default
... how can I augment this function to include in the search the 'contacts' array within each 'project' object, e.g.:
return this.projects.filter((project) => {
return (project.businessName.toLowerCase().match(searchTerm)) ||
(project.reference.toLowerCase().match(searchTerm)) ||
// PSEUDO-CODE (searching contact name doesn't throw error but returns 100% of the data):
(project.contacts.filter((el) => {
el.name.toLowerCase().match(searchTerm);
}))
});
Thanks in advance for any help or suggestions,
Whiskey T.
asked Feb 1, 2018 at 18:10
1 Answer 1
Two things:
filter
returns an array, so its value will always be true; you need to check thelength
of it to get a false value when it's empty- you need a
return
in yourproject.contacts.filter
arrow function
answered Feb 1, 2018 at 21:03
Comments
lang-js
(projects.contacts.filter(.....).length > 0)
return
in front ofel.name
filter
returns an array, which is a truthy value even if it's empty. The other expressions are usingmatch
.