Using a Vue computed property updates the values within the data object

My data structure (this.terms) looks like this:

{
    name: 'First Category',
    posts: [
        {
            name: 'Jim James',
            tags: [
                'nice', 'friendly'
            ]
        },
        {
            name: 'Bob Ross',
            tags: [
                'nice', 'talkative'
            ]
        }
    ]
},
{
    name: 'Second Category',
    posts: [
        {
            name: 'Snake Pliskin',
            tags: [
                'mean', 'hungry'
            ] 
        },
        {
            name: 'Hugo Weaving',
            tags: [
                'mean', 'angry'
            ]
        }
    ]
}

I have a method that filters this.terms by tags and outputs the computed results.

computed: {
    filteredTerms: function() {
        let self = this;
        let terms = this.terms;

        if(this.search.tags) {
            return terms.filter((term) => {
                let updated_term = {}; 
                updated_term = term;

                let updated_posts = term.posts.filter((post) => {
                    if (post.tags.includes(self.search.tags)) {
                        return post;
                    }
                });

                if (updated_posts.length) {
                    updated_term.posts = updated_posts; 
                    return updated_term;
                }
            });
        } else {
            return this.terms;
        }
    }
},

The filteredTerms() method returns categories with only matching posts. For example, a search for "angry" returns just "Second Category" with only "Hugo Weaving" listed.

The issue is that running the computed function changes Second Category in this.terms instead of in the copy of it (terms) within the function only. The line causing this is updated_term.posts = updated_posts. It seems to also alter this.terms. Resetting the entire data object every time isn't ideal as it would require loading everything again. I need this.terms to remain untouched so I can revert back to it after clearing search criteria.

I've tried different approaches like using lodash versions of filter and includes, as well as using loops and push(), but the issue persists. Any insights would be appreciated. Thank you for your help.

Answer №1

Consider cloning the object instead of referencing it. Here is an example of how you can achieve this:

let words = [];
Object.assign(words, this.words);

Answer №2

let values = this.values;

Instead of duplicating the array, it simply creates a reference to this.values. The rationale behind this is due to JS objects and arrays being reference types. Refer to this informative video for further clarity: https://www.youtube.com/watch?v=9ooYYRLdg_g

To make a copy of the array, utilize this.values.slice(). In case of an object, you can employ {...this.values}.

Answer №3

I made an enhancement to my compute function by adding the following code snippet:

let items = [];
for (let j = 0; j < this.items.length; j++) {
    const item = this.copyItem(this.items[j]);
    items.push(item);
}

Additionally, I implemented a method called copyItem() so that I can utilize it in other parts of my code. Here is the implementation of the copyItem() method:

copyItem: function (source) {
    return Object.assign({}, source);
}

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

Trouble with CSS loading in Vuetify causing delays

While working on my webapp using Nuxt.js + Vuetify, I encountered a delay in the CSS of certain elements after deploying it on Google App Engine. You can see an example of this delay in this GIF. Is there a way to prevent or fix this delay? ...

Mastering Meteor: Techniques for Manipulating Mongodb Data in Real Time Display

Within my Meteor application, I have accomplished the successful publication of data from the server and its subscription on the client side. Instead of directly displaying raw data on the client's screen, I am interested in performing some calculatio ...

Creating a specific type of table using Ruby on Rails

Is it feasible to create a table with two columns, where the left column incorporates multiple rows with a scroll bar, and the right column contains a large box housing buttons that alter based on the selection of blocks in the left column? ...

The pinia state value fluctuates as the muted props value shifts

I have encountered an issue in my application where I utilized the Pinia store and event emit implementation to mutate props value from a child component to its parent. However, both values are now reactive, causing changes in one to reflect in the other. ...

What is the best way to set an initial value retrieved from the useEffect hook into the textField input field?

I am working on an edit page where the initial values of first name, last name, and address are fetched from Firebase Firestore using useEffect. useEffect(() => { const unsubscribe = firestore .collection("users") .doc(uid) ...

Discord between Bootstrap tabs and C3 charts: A Compatibility Str

On my website, I have implemented Bootstrap navigation tabs that each contain a chart. The issue I am facing is that when I navigate to the home page, the chart in the active tab displays perfectly fine. However, for the other tabs, the charts overlap with ...

Having trouble with your Vue.js 2.0 project? Encountering a Module build failure due to an Unexpected token error while using webpack,

Struggling throughout the day to upgrade from Vue.js 1.X to Vue.js 2.0 resulting in errors (using gulp watch) has left me feeling frustrated. ERROR in ./~/buble-loader!./~/vue-loader/lib/selector.js?type=script&index=0!./resources/assets/js/compon ...

Tips on changing an image with a button click

I am currently working on a project where I have a div tag containing an image that is selected randomly from different arrays based on topics. However, I am facing some challenges in making the image change when the "go" button is clicked. I want the if ...

Enhancing JavaScript Asynchronous Programming with EventLoop and async/await

Exploring the intricacies of how JavaScript processes asynchronous methods led me to dive into async/await. In an effort to gain a complete understanding, I crafted the following example: async function first() { console.log(9); await Promise.resolv ...

How can you iterate over the input elements that are currently visible within a form using Javascript?

Is there a way to clear the values of all visible input fields in a form using JavaScript? I'm currently struggling with setting text inputs to empty as they come out as undefined. Any suggestions on how to achieve this? ...

Rotate background image upon each visit

I have a collection of around 50 background images that I want to display randomly each time a user visits my website. The idea is to provide a unique background image for every visit, without saving any information about which image was previously display ...

What are the steps to execute a module designed for NodeJS v6 LTS ES2015 in Meteor 1.4.x?

While I understand that Meteor includes NodeJS as a dependency, I'm facing an issue with a module written in ES6 that has a default argument value set within one of the Class methods. The problem arises when using Meteor v1.4.3.2: (STDERR) packages/m ...

Tips for executing mocha tests using a reporter

Whenever I execute the command npm test, it displays this output: mocha ./tests/ --recursive --reporter mocha-junit-reporter All the tests are executed successfully. However, when I attempt to run mocha with ./tests/flickr/mytest --reporter junit-report ...

Align component within material-ui grid

Looking to center align the same cards but not just the grid component, I need the content itself to be equally distant from the borders and each other. I've searched and tried different solutions without luck. https://i.stack.imgur.com/aZj7H.png htt ...

Ways to retrieve the value of a specific key within an object nested within another object

Suppose I have a variable named x with the following structure: x = { choice1: { choice: { name: "choice1", text: "abc", key: "key1" } isChecked: true }, choice2: { choice: { name ...

Unexpected behavior observed: Title attribute malfunctioning upon double clicking span element

I recently implemented the following code: <span title="hello">Hello</span> Under normal circumstances, the title attribute functions correctly when hovering over the element. However, after double clicking on the span element (causing the t ...

Oops! An unexpected field was encountered while trying to use the uploadMultiple function from dropzone.js

I was looking for a way to allow users to select images to accompany their reviews. That's when I came across dropzone.js. However, I encountered an issue when trying to send multiple images in one request. I expected the req.files to contain an arra ...

The TextBox will alter its color following an incorrect submission

I am struggling to create a bootstrap form that will change the color of the borders to red after incorrect submission. The issue I am facing is that the textbox always remains in red. Does anyone have any suggestions for setting the textbox borders to red ...

Are MobX Observables interconnected with RxJS ones in any way?

Is the usage of RxJs observables in Angular comparable to that in React and MobX? I'm struggling to find information on this topic. ...

Issues arise when props do not get transferred successfully from the getStaticPaths() to the getStaticProps

I have successfully generated dynamic pages in nextJS from a JSON using getStaticPaths(). However, I am facing an issue where I am unable to access the information within the JSON. I pass it as props to getStaticProps(), but when I try to console log it, i ...