No search results found when using Vue.js searchbar filter

Today I delved into the world of VUEjs for the first time, experimenting with extracting data from a URL in JSON format. Initially, this process went smoothly, but my curiosity led me to attempt adding a search feature. I followed online tutorials, which unfortunately did not yield the desired results. Upon incorporating a filter() method into my code, the screen went blank. This hiccup has left me at an impasse as I struggle to identify where I might have gone wrong.

For instance, writing "Bitcoin" should ideally return the symbol, name, and price of the cryptocurrency.

<div id="app">
   <input type="text" v-model="search" placeholder="search coin">

   <ul>
       <li v-for="coin in filteredCoins">
           {{ coin.symbol }} {{ coin.name }} {{ coin.quotes['USD']['price']}}
       </li>
   </ul>
</div>

<script src="https://unpkg.com/vue"></script>
<script>
const app = new Vue({
    el: '#app',
    data: {
        data: [],
        search: ''
    },
    computed: {
        filteredCoins: function() {
            return this.data.filter((coin) => {
                return coin.title.match(this.search);
            });
        }
    },
    created () {
        fetch('https://api.coinmarketcap.com/v2/ticker/')
            .then(response => response.json())
            .then(json => {
                this.data = json.data
            })
    }
})
</script>

Codepen

Answer №1

An object, unlike an array, is what you'll find in <code>json.data
, which means filter won't work on it. To filter it, you must first transform that object into an array. You could follow the approach suggested by Bert in his codepen.

computed: {
  filteredCoins () {
    return Object.values(this.data).filter(coin => coin.name.toLowerCase().match(this.search.toLowerCase()))
  },
},

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

Ditch the if-else ladder approach and instead, opt for implementing a strategic design

I am currently working on implementing a strategic design pattern. Here is a simple if-else ladder that I have: if(dataKeyinresponse === 'year') { bsd = new Date(moment(new Date(item['key'])).startOf('year&apos ...

Sort an array using a custom sorting algorithm in Javascript

In my current function, I am able to sort an array alphabetically. function compare(a,b) { if (a.subtitle < b.subtitle) return -1; if (a.subtitle > b.subtitle) return 1; return 0; } Now, I am in need of a similar fun ...

Tips for preventing redirection in Vue 3 composition API with asynchronous requests

I have successfully configured a submission form to send data to my email and add it to a Google sheet using the method described in this GitHub link. The process worked seamlessly for both purposes. However, I am facing an issue where upon submitting the ...

Error in Typescript: Function not being triggered on button click

As someone who is just starting out with typescript, I've been tackling a simple code that should display an alert message in the browser when a button is clicked. I've experimented with the button and input tags, as well as using both onclick ev ...

AnugarJS - Issue with Object Array not refreshing in view after pushing an item

After adding a new element to my object array, I'm having trouble getting it to reflect in the view. Can anyone offer assistance? This is my first time working with AngularJS. My Code Javascript var App = angular.module('App', []); App.c ...

Adding a static javascript file to a Vue CLI 3 project is a straightforward process

Currently working on a vue-cli-3 project and looking to include a static javascript file. Curious about the proper way to import this file. The typical method used is: <script src="js/myfile.js"></scrip> ...

Prevent page refresh when submitting a form using PureCSS while still keeping form validation intact

I'm currently implementing PureCSS forms into my web application and facing a challenge with maintaining the stylish form validation while preventing the page from reloading. I discovered that I can prevent the page reload by using onsubmit="return f ...

The regular expression is functioning correctly in the browser, however, it is encountering issues when

My task involves identifying certain strings from given variables. Let's say I have a variable: var x = 'elseif testing'; My goal is to extract the value "testing" from this string, so I came up with the following code snippet: x.match(/^ ...

Interacting Sibling Components in React: How Button Presses Facilitate Communication in a Login Form

I am trying to establish communication between sibling components in my React application. The idea is to have separate components for the Username and Password fields, with another button component that will request the values from these components and pe ...

Is there a way to enlarge an image to fullscreen when clicked on?

I'm working on a table that contains images and I want to implement a feature where clicking on an image will make it fullscreen, and then clicking on the fullscreen image will return it to the table. I am developing this using PhoneGap for mobile d ...

Error: Jasmine unit test failed due to a connection refusal

While running the unit test in jasmine using the ng test command, an error occurred. Previously, everything was configured correctly and working well. I'm not sure why this error suddenly appeared. Error message in browser: Description: Connection ...

Killing chromedriver.exe programmatically using Java Script

Currently, I am utilizing Protractor to automate tasks within my application. One of the requirements I have involves the explicit termination of chromedriver.exe. In Java, I would typically use Runtime.getRuntime().exec("TASKKILL /F/IM chromedriver.exe") ...

What are some tips for reorganizing data in an array?

My PHP function is currently outputting separate arrays instead of one indexed array. How can I modify the code to concatenate these outputs into a single array? Any suggestions or clarifications would be greatly appreciated. This is the current output: ...

A guide on integrating the vue3-openlayers plugin into a Nuxt project

I am currently working with Vue3 and have the main.ts file set up as follows: import { createApp } from "vue" import App from "./App.vue"; //In the context of nuxt3, how can I include OpenLayersMap? import OpenLayersMap from "vue3 ...

Guide to using an existing array with a ListView in Android

I am trying to use a ListView to display some text on the screen. Here is what I have attempted: Standings[] addressArray = new Standings[18]; ... Arrays.sort(addressArray, StandingsSort.ORDER_BY_RULES); ArrayAdapter adapter = new ArrayAdapter<Strin ...

The onchange tag fails to trigger my Javascript function when selected

Here is the code I have: JS: function updateLink() { var selType = document.getElementByID("Types"); var selLen = document.getElementByID("Length"); var selLoc = document.getElementByID ...

The request to delete http://localhost:3000/people/[object%20Object] returned a 404 error, indicating that the resource

I've been attempting to remove a person from my table using the following function: const deletePerson = async (id) => { await fetch(`http://localhost:3000/people/${id}`, { method: "DELETE", headers: { "Cont ...

Troubleshooting Vue.js: Overutilization of EventBus causing repeated function calls

I'm in the process of implementing an 'undo delete' feature. To achieve this, I am utilizing an Event Bus to broadcast an event to two separate components as shown below: Undo.vue: EventBus.$emit(`confirm-delete-${this.category}`, this.item ...

I possess an assortment of objects and I must retrieve specific information about them based on two data points

Managing a collection of items can be challenging, especially when filtering based on specific data points. For example, let's say we have a collection of action objects like {name: Detail}, {name: Spec}... and two data points determining which action ...

Determine the file format using fs module in Node.js

I have a question about extracting file types or extensions from a folder. I have multiple files in a folder, and I want to retrieve the type/extension of the file that matches a randomly generated number stored in my num variable. Is there a way to achiev ...