Exploring Vue.js for array searching

I am attempting to search through an array to find a query string within a JSON object. The results are filtered and displayed as an array, but currently only the name field is being returned, not the number field.

      computed: {
        search: function () {
          let self = this
          let filtered = []

          filtered = self.jcontacts.filter(function(contact){
            return  contact.firstname.toLowerCase().indexOf(self.query.toLowerCase())>=0 ||
                    contact.lastname.toLowerCase().indexOf(self.query.toLowerCase())>=0;
                    //contact.email.toLowerCase().indexOf(self.query.toLowerCase()) >=0 || - Removed for better performance
                    //contact.phonenumber.toLowerCase().indexOf(self.query.toLowerCase()) >=0; - Removed for better performance
            }
          );
          return this.contacts = filtered
        }
      },
    }

The issue with the number not appearing in the filtered method is due to how it's structured. Here is an example of the JSON data:

[ { "id": 1, "phoneNumber": [ "3908902" ], "email": [ "[email protected]" ], "firstname": "Jamie", "lastname": "Fox" }]

Answer №1

  1. Be cautious of the case sensitivity issue with phoneNumber != phonenumber
  2. Remember, phoneNumber is stored as an array not as a string, so searching for it requires different method (consider using .includes() function)
  3. To improve code readability, it's advisable to save self.query.toLowerCase() as a variable or another computed property

Answer №2

There appears to be a typographical error. The field phoneNumber should be filtered as phonenumber instead.

Since it is an array, you can accomplish this by:

contact.phoneNumber.forEach( number => { 
   if(number.toLowerCase().indexOf(self.query.toLowerCase()) >= 0) 
      return true;
});

You may also follow a similar approach for the email field, considering that it is an array as well.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What are some ways to incorporate TypeScript into a function component to enforce type constraints and set default values?

I have a function component similar to the example provided. I am familiar with using PropTypes to define prop types and default values in React, but my team has transitioned to TypeScript. Can anyone help me understand how to achieve the same in TypeScrip ...

Modify the nearest symbol after the (touch) operation on Angular version 6

On my list, I have caret icons displayed on the left side which should change when clicked. Clicking on one icon should trigger a change in all other icons as well. <div class="caret" *ngIf="summary.isSupervisor" style="position: absolute; left: 15px ...

Encountering problem with image file encoding while using res.download in Express.js

My node.js server with expressjs is set up for local development, where I store and retrieve various files through basic HTTP calls. Most of the time, everything works smoothly. However, on rare occasions, a small number of files return to the end-user sig ...

Angular sends a blank object to the server

Utilizing angular along with spring boot 2 has presented a challenge for me. Each time I attempt to send a POST request, spring validation messages pop up indicating that my fields cannot be empty or null. Here is the form structure of my POST request: < ...

Retrieving a MAC address from a device using a web script or HTTP protocol

Is it feasible, with access to all end user devices, to request the device's MAC address using web scripting in Apache/IIS/Nginx? Would PHP, Perl, or ASP be able to accomplish this task? The client devices run on iOS, so the method described here wil ...

Harnessing the power of $map in MongoDB for updating objects within query pipelines

After retrieving a list of objects from a call to db.collection.aggregate(), the results look like this: { _id: <some_id>, count: 400, results: [ { _id: 1, ... travel_guess: 0.1934042214126773, }, { _id: 2, ...

Tips for sharing data between two components

In my project, I have a customized Shared Component which consists of an input search bar with a "continue" button. This Shared Component is being utilized within two other components - the buy component and sell component. The challenge I am encountering ...

using the image source in the onclick function

I have implemented the following code to convert an image to grayscale using Javascript. <body> <canvas id="myCanvas" width="578" height="400"></canvas> <script> function drawImage(imageObj) { var canvas = document.getElement ...

What is the best way to incorporate a dropdown header in Material-UI on a React project?

I am facing an issue where only the last Menu Dropdown is rendering, but I actually need different Menus to be displayed (with the text faintly appearing behind them). I am uncertain about how to correctly pass the props/state to make this work. import Rea ...

Tips for delaying the execution of the next function until after a Firebase storage image upload is complete

I'm currently working on a function that involves uploading multiple images to Firebase, storing the returned URLs in an object, and then uploading that object to my Cloud Firestore database. However, my understanding of async/await and promises is li ...

Using an array as a condition allows us to extract substrings in

I'm dealing with a file that contains text. ABBCDE1990-12-10JOBALPHABETabbcde1990-12-10jobalphabet $field = array( "fullname" => array("length"=5,"mandat"=>True), "bithday" => array("length"=>10,"mandat"=>True) "job" => a ...

"Simultaneously creating a Firebase user account and populating the database with user

My goal is to store new user information in my database using their unique user UID when they sign up through Firebase. Currently, my code is functioning properly, however, I am facing an issue where the name (which should be the created user UID) appears ...

React doesn't have file upload configured to update the state

I am working on integrating a file upload button that sends data to an API. To ensure only the button triggers the upload dialog and not the input field, I have set it up this way. Issue: The File is not being saved to state, preventing me from using a ...

Utilizing numerous asynchronous await calls within a promise

Having trouble with my nodejs script that uses async await to save emails and recipients to a database. The issue is the last email and recipient are not being saved. Can't figure out what's wrong. Here's the relevant code: function saveEma ...

Setting properties on a Vue component that refer to both the parent and the component itself can be tricky. Be cautious when attempting

Within my component, I often use it as a nested component with multiple levels of components and also as a mounted component through vue-router. The challenge arises when deciding whether to pass data from the parent or set it directly within the component ...

Why do `setTimeout` calls within JavaScript `for` loops often result in failure?

Can you help me understand a concept? I'm not inquiring about fixing the code below. I already know that using the let keyword or an iffe can capture the value of i. What I need clarification on is how the value of i is accessed in this code snippet. ...

What is the desired length for the Array variable?

Currently working on developing iOS applications with C++ Builder. I have created an array of TImage in my application. TImage *Image[10] ; The issue is that I do not know the exact length of the array during runtime. How can I set a variable array len ...

Transferring information among offspring components

I am having difficulty getting this to work. I need a way to access the value of selected in the ChooseLangComponent from the FormComponent. Is there a direct method to achieve this or do we have to pass it through the parent component (acting as a middle ...

My React setup is causing some problems that I need to address

React is not my strong suit, but I need to test a React application. The issue arises when attempting to run the server using gulp nodemon, resulting in numerous errors. It seems that the application is built on an outdated version of React and some libra ...

creating a JSON response using PHP

I've been struggling to work with JSON responses that have a complex structure, and despite multiple attempts, I can't seem to figure it out. The desired JSON response should look like this: "note": { "vote": 3, "items":[ { ...