0

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
6
  • (projects.contacts.filter(.....).length > 0) Commented Feb 1, 2018 at 18:57
  • @RoyJ Thanks for the response. As your suggestion shows closed parens around the filter arg, I assume you mean: '(project.contacts.filter((el) =>{ el.name.toLowerCase().match(searchTerm); }).length > 0); ... but this is not returning any results where expected. What have I misunderstood? Thx Commented Feb 1, 2018 at 19:16
  • You need a return in front of el.name Commented Feb 1, 2018 at 19:19
  • @RoyJ Thank you; yet another 'duh' moment as to the 'return' ... however would you mind explaining why the length method is required on the contacts filter but not in the filter of the outer objects? Commented Feb 1, 2018 at 19:28
  • Because filter returns an array, which is a truthy value even if it's empty. The other expressions are using match. Commented Feb 1, 2018 at 19:30

1 Answer 1

1

Two things:

  1. filter returns an array, so its value will always be true; you need to check the length of it to get a false value when it's empty
  2. you need a return in your project.contacts.filter arrow function
answered Feb 1, 2018 at 21:03

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.