Filtering properties of objects in Vue

I am currently dealing with an array of objects that represent continents:

data() {
    return {
        continents: [
            {
                name: "South America",
                countries: [
                    {
                        name: "Paraguay"
                    },
                    {
                        name: "Chile"
                    }
                ]
            },
            {
                name: "North America",
                countries: [
                    {
                        name: "Costa Rica"
                    },
                    {
                        name: "Mexico"
                    }
                ]
            }
        ]
    }
}


// There are a total of 6 continents and over 250 countries.

I am attempting to apply a filter using v-model called 'filter' like this

computed: {
    filtered() {
        return this.continents.filter(continent => {
            continent.countries = continent.countries.filter(country => {
                return country.name.match(new RegExp(this.filter, 'i'));
            });
            return continent.countries.length;
        });
    }
}

To display the results, I use the v-for directive in the following way:

<input v-model="filter" type="text">
<div v-for="continent in filtered" v-if="filtered.length" class="countries-group">
    <h4>{{ continent.name }}</h4>
    <ul class="country-list">
        <li v-for="country in continent.countries" class="country-item">{{ country.name }}</li>
    </ul>
</div>

The process is almost successful, however my computed property 'filtered' is altering the original data for countries. This causes issues when trying to delete characters from the filter applied through v-model, as it does not revert back to the initial data due to the modifications made by the filter.

Answer №1

After implementing my updated computed property filter, the original data of countries is altered.

It is advised to avoid modifying state within computed properties as it can lead to unexpected bugs by triggering re-evaluation of other computed properties. Computed properties should remain pure functions that transform the component's state without mutating it.

Here is a recommended approach:

filter() {
  const searchFilter = this.search.toLowerCase();

  return this.world
    .map(continent => Object.assign({}, continent, {
      countries: continent.countries.filter(country => {
        return country.name.toLowerCase().includes(searchFilter);
      }),
    })
    .filter(continent => continent.countries.length);
}

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

In Vue, a computed property is rendered as regular text on the screen

Is there a way to format the title using HTML spans instead of plain text? Here is the code: spanTitle() { return this.title.replace(/([A-Za-z0-9'<>/]+)/g, '<span>$1</span>'); } {{ spanTitle }} this.title = "Upc ...

What is the best way to position my Jchartfx area graph below my gridview?

When my page loads, the graph appears like this. It consistently shows up in the top left corner even though it should be positioned underneath the grid view as intended. var chart1; function createGraph(mpy) { if (mpy == undefined) mpy = 12.00; ch ...

Combining Flask with Ajax: AttributeError - WSGIRequestHandler does not have the attribute 'environ'

Currently, I am working on using ajax to trigger the execution of a Python file that continuously monitors changes in a text file. If any changes are detected, it will communicate back to ajax for further actions. The Python script must start running as so ...

What is the best approach for accessing values from dynamic or multiple form fields upon submission in React?

In my form, users have the ability to add Textfields in order to include additional items. However, I am facing a challenge when it comes to retrieving these items from the form upon submission. The Textfields are dynamically created by a component functi ...

I have a task of extracting information from a live Google map and generating a static Google map using API V3

I am working on a project that involves allowing users to create maps using Google Maps and then save the image. My current workaround uses both the Google Maps API V3 and the Static Maps API. The user can interact with the dynamic Google map by scrolling ...

The JSON response did not trigger the AJAX callback function

My AJAX function, written in coffeescript, is successfully returning values. However, neither the error nor the success callbacks are being triggered. $ -> $('#sf_field').autocomplete source: (request, response) -> $.ajax ...

working with json files in node.js

I have encountered an issue with manipulating a JSON file using Node.js. Here is the scenario: { "joe": { "name": "joe", "lastName": "black" }, "matt": { "name": "matt", "lastName": "damon" } } Now, I n ...

Having issues with a local image not loading in React?

I am trying to display a local image in React js. After referring to this solution, I have tried the following code - <img src={require('../public/images/icon.png').default} /> The image "icon.png" is stored in my public folder, and I&apos ...

In Angular, when a component is clicked, it is selecting entire arrays instead of just a single item at a

I am currently working on implementing a rating feature using Angular. This component will be used to rate different languages based on how proficient I am with them. My issue lies in the fact that when I click on one array element, it automatically selec ...

Preparing my JSON data for visualization on a chart

I have successfully retrieved data using this API, but now I need to transform it into a chart within my react project. As a newcomer to JS and React, I am struggling to create a chart with the JSON data. My objective is to display prices by bedrooms over ...

The JavaScript code is not being executed, as the address bar displays the function name instead

In my project, I have created numerous "js-classes" with various functions spread across different files. Unfortunately, the codebase is too large to share entirely. However, towards the end of the project, I encountered a bug where a specific function wa ...

Backend JS error found in Joomla 3.0 Component

Currently, I am working on developing a custom Joomla 3.0 component. To begin, I started by downloading the com_hello component sample from the official Joomla documentation. However, I've encountered an issue when trying to check the checkbox in the ...

Swap out internal Wordpress hyperlinks for Next.js Link Component

Currently, I am working on a project where I'm using WordPress as a headless CMS with GraphQL for my Next.js app. Most aspects are running smoothly except for the internal content links within articles that are fetched through the WP API. These links ...

Improprove the design of the dropdown component using React

One of the challenges I am facing in my project is using multiple dropdowns from semantic-ui-react. Each dropdown needs to have different props, making the code look like this: <div className="wrapper"> <img className="icon" src={iconA} ...

Tips for concealing the cursor indefinitely in Typed JS

Is there a way to hide the cursor permanently in TypedJS so that it doesn't blink or show while typing? I've come across tutorials on hiding it after typing is complete, but not from the beginning. Any suggestions on how to achieve this? ...

The dynamic importing of a component does not function correctly when the component path is stored in a variable

Technology Stack Using Vue version 3.2 Nuxt version 3.0.0-rc.4 Vite version 2.9 Main Objective The main goal is to dynamically load a component using <component :is /> from a variable rather than a static string. Sample Code Below is a concise ex ...

Utilizing JQuery to Implement ngModel and ngBind in Angular Directives: A Step-by-Step Guide

[Note] My objective is to develop custom Angular directives that encapsulate all the necessary JS for them to function. The directives should not know what they are displaying or where to store user input values; these details will be passed in as attrib ...

Exploring the Differences between Angular's Http Module and the Fetch API

While I grasp the process Angular uses for HTTP requests, I find myself leaning towards utilizing the Fetch API instead. It eliminates the need to subscribe and unsubscribe just for a single request, making it more straightforward. When I integrated it int ...

Retrieving the response value in AngularJS with $resource

I'm trying to retrieve the response of a request using $resource in AngularJS. Here is an example implementation: angular.module('app').factory('AuthResource', ['$resource', function($resource) { return { isA ...

Instead of sending a post request, sending an options request after the ajax request is made

Currently, I am initiating a post ajax request: var responsehttpreq = {} function createAndSendXmlHttpReq(){ requestBody = { hostname: "prova", pathname: "prova", query: "prova", method: "prova" } console.log("F ...