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

Unveiling the Technique: Adjusting Field Visibility When Dropdown is Altered

I tried to find a solution on Stackoverflow for displaying/hiding a field based on dropdown selection using either jQuery or inline JavaScript. However, I am facing difficulties when implementing this within a table. Let's start with an easy approach ...

Checking the dimensions and information of a JSON collection - a step-by-step guide

Recently, I've encountered a JSON String that was returned with an array inside in my Java SpringBoot application. {... "downlineLevels": ["01","02","03","04","05","06","07"] } Unfortunately, only the following JUnit tests have passed. 1) .andExpec ...

The content inside a Textbox cannot be clicked on. I am seeking help with implementing JavaScript to enable it to be

As a newcomer in the world of programming, I am sharing a snippet of my JavaScript and HTML code with you. I am facing an issue where I want to enable users to start typing in a text box upon clicking on the text "User Name", without deleting any existing ...

Looking for a Javascript tool to select provinces graphically?

Looking for a graphic province selector similar to the one found on this website: . If anyone is aware of something like this, especially in the form of a jQuery plugin, that would be fantastic. Thank you. ...

Utilize the i18n tag for seamless translation

I am facing a challenge with my latest Vuejs project. I have implemented vuei18n similar to another project in my company, however, the tag is not working correctly in the new project. After turning off <code>silentTranslationWarn in i18n/index.js, ...

Remove the active class after it has been clicked for the second time

Currently, I am working on a menu/submenu system where I want to toggle active classes when clicked. However, I encountered an issue - if the same menu item is clicked twice, I need to remove the active class. Initially, I tried using jQuery's toggleC ...

Stop ngOnChanges from being triggered after dispatching event (Angular 2+)

In Angular 2+, a custom two-way binding technique can be achieved by utilizing @Input and @Output parameters. For instance, if there is a need for a child component to communicate with an external plugin, the following approach can be taken: export class ...

When a user clicks on an anchor tag, the corresponding value of the checked item is then returned

I have 3 sets of radio buttons. When a specific anchor with the "round" class is clicked, two actions should occur: The associated set of radio buttons needs to become visible The value of the checked input for that element should be returned. I am ...

What methods can users employ to effectively manage and maintain their in-app purchases using my application?

Hey there, I could really use some assistance. Recently, I created a mobile app for a client that allows users to purchase and watch video courses. However, I'm facing an issue where when a user buys a course and then refreshes the app, they are redir ...

Error encountered during Yarn installation process: The tunneling socket was unable to be established due to a connection refusal on localhost at port 80

I have a Next.js app that needs to be built on our company servers before deployment. We use a proxy, and I've configured yarn to use the proxy as well. yarn config set proxy http://xx.xxx.xx:xxxx yarn config set httpsProxy http://xx.xxx.xx:xxxx yarn ...

What steps should I take to delete a class from my calendar after it has reached the maximum capacity of 20

I am trying to create a feature that automatically removes a class from the calendar if more than 20 people have booked it. On the admin side of the system, I can add classes to the database but need help implementing this check. Below is my current code ...

The Controller is failing to pass JSON Data to the AJAX Call

When trying to access JSON data in the Controller, it is not being retrieved in the Success function and instead showing an error message "Failed to load resource: the server responded with a status of 406 (Not Acceptable)" or executing the Error function. ...

choose multiple elements from an array simultaneously

Looking for help with a basic Array question and seeking the most effective solution. The scenario involves having an array: var pathArr = [element1, element2, element3, element4, element5, element6] If I want to select multiple elements from this array ...

Combining arrays using JavaScript

I'm struggling to enhance the following code - it looks a bit messy: Here is my data format: date d1 d2 d3 d4 d5 d6 110522 5 1 3 5 0 7 110523 9 2 4 6 5 9 110524 0 0 0 0 1 0 110525 0 0 3 0 4 0 ... I am importing data from a text file using d3.j ...

Unexpected behavior observed when trying to smoothly scroll to internal links within a div, indicating a potential problem related to CSS dimensions and

Within a series of nested div containers, I have one with the CSS property overflow:hidden. My goal is to smoothly scroll to internal links within this specific div using jQuery. The snippet of code below has worked successfully in previous projects: ...

Combining CodeIgniter4 with Vue.js and Webpack's devServer to handle CORS issues

Exploring Vue & CodeIgniter 4, starting from https://github.com/flavea/ci4-vue. No matter what I try, I encounter a persistent CORS error in dev mode: Access to XMLHttpRequest at 'http://example.com/public/api/book/get' from origin &apo ...

Encountered an issue with reading the property 'drop' from an undefined source during a straightforward migration

I recently started using the migrate-mongo library and encountered an issue during a simple migration process to create a view. Despite success in migrating up, I faced an error when attempting to migrate down. ERROR: Could not migrate down 20220620114132 ...

Managing pagination within the Vuex state management system: a guide

After finding this amazing shopping cart repository on https://github.com/vueschool/learn-vuex, I successfully cloned it and the retrieved data appears like this: ProductList.vue <template> <div> <ul> <li v-for="product ...

How can I include inline CSS directly within a string instead of using an object?

Is there a way to write inline CSS in a string format instead of an object format? I attempted the following, but it did not work as expected: <div style={"color:red;font-weight:bold"}> Hello there </div> What is my reason for want ...

Why does it appear that Angular is undefined in this straightforward Angular demonstration?

I'm completely new to AngularJS and I've encountered an issue. Yesterday, I ran a very simple AngularJS application that I downloaded from a tutorial and it worked perfectly. The application consists of 2 files: 1) index.htm: <!DOCTYPE htm ...