Incorrect variable being updated in Vue.js

I created a filter method called itemsWithFilter to filter the items object and store the results in itemsResult.

This function initially works as expected, but I noticed that it automatically updates the original items object. However, I intended for the results to only be written to itemsResult.

Can anyone explain why this is happening and suggest ways to prevent it? I want the itemsWithFilter method to exclusively return its results to itemsResult.

Here is the Fiddle link: https://jsfiddle.net/afdz3yLt/1/

Below is my implementation of the itemsWithFilter function

itemsWithFilter: function(filter) {

  var items = this.items.data;
  var result = {}

  console.log("Run itemsWithFilter")
  Object.keys(items).forEach(key => {

    const item = items[key]

    console.log(`filter: ${filter}: checking item ${item.id} with category id: ${item.category.id}`)

    if (item.category.id == filter) {
      result[key] = item;
    }
  })

  this.itemsResult.data = result;

}

Answer №1

It's possible that I may be misunderstanding the question, but it seems like you are asking how to utilize this.items.data and write the output to this.itemsResult.data without affecting this.items.data. In JavaScript, object references always remain unchanged by default. If I have interpreted your question correctly, what you need is to clone the this.items.data object. The recommended approach for achieving this is

var items = JSON.parse(JSON.stringify(this.items.data))
. For more details, refer to these related questions:

How to copy JavaScript object to new variable NOT by reference?

What is the most efficient way to deep clone an object in JavaScript?.

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 advantages does Angular Service offer when gathering information compared to utilizing only $http?

Comparing Two Approaches: Approach A. Creating app module Using a service to store model data Implementing a controller to retrieve data from the service File 1: Users.js: angular.module('users', []); File 2: userService.js: angular ...

Can you provide guidance on how to increase the value within a nested object located inside an array within another object?

In my attempt to create a bot in discord.js, I am facing a challenge where I need to implement an inventory system with items that have durability. The data is stored in MongoDB Atlas and the structure of the inventory is as follows: user: { id: 'us ...

What is the best way to organize and group messages in JavaScript in order to push them to a subarray?

Having trouble coming up with a name for this question, but here's the issue I'm facing: I currently have an array in PHP containing several entries. Array ( [0] => stdClass Object ( [sender_id] => 0 [me ...

Certain videos may display as a blank white screen on mobile devices when utilizing an HTML5 video tag

I'm currently working on a React app that allows users to upload videos from their devices. The uploaded video is then displayed on the webpage using a <video> tag. During testing, I encountered an issue where some specific videos would only sh ...

Guide to putting a new track at the start of a jPlayer playlist

I am currently working on a website that utilizes the jPlayer playlist feature. I am facing an issue, as I need to implement a function that adds a song to the beginning of the playlist, but the existing add function only appends songs to the end of the pl ...

When using addClass("test"), it throws an error message: TypeError: undefined is not a function

Upon examination in the console, I discovered the following: $(".myCssClass")[0].parentNode <li><span class="myCssClass">some text</span></li> I am attempting to add a CSS class to the parent span tag within the <li> element ...

Accessing the properties of a module in Javascript - a foolproof guide to making the most

In the constants.js file, I have defined the following code: var constants = ( conversationUsername: "user1", conversationPassword: "pass1", conversationVersionDate: "date1", conversationWorkspaceId: "work1" }; module.exports.constants ...

Is there a way to use JavaScript or jQuery to identify if Firefox is blocking mixed content

Is there a way to detect when Firefox (or any browser) is blocking mixed content using JavaScript or jQuery? To learn more about Firefox's mixed content blocking feature, visit: The backstory: My company has an external vendor that handles the onli ...

An error has occurred in the Nuxt.js environment: `document is not defined` specifically related

Despite my efforts, I can't seem to get rid of this persistent error...:( First. the issue- The "vuejs-datepicker" component works perfectly on initial page load. However, upon reloading the page, a "Reference Error" pops up... error screensho ...

Saving User Identification on Client-Side Application to Make API Requests

Currently, I have a Node-Express REST API that allows for making a GET request to a user controller - /users/:id. The user-id number is stored in the database. Additionally, there is a React-Redux client-side app that communicates with the API. To make thi ...

Creating fresh fields using AngularJS

I'm looking to dynamically create a new form whenever an item is added to an array. The form remains consistent, but the conditional count increases each time. Here's an example: <span ng-show="companydata.selectedloc.length == 0"> &l ...

Exclude objects in array that do not match filter criteria

I am facing a challenge with filtering an array of objects. (9) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}] 0: {tbi_tblid: 512100013, long_name: "", short_name: "", short_name2: "", trickysort: "", …} 1: {tbi_tblid: 512100013, long_n ...

Error: Installation of component unsuccessful in nuxt.js

After creating a new file called testcomp.vue, I added the following code in pages/index.vue: import testcomp from 'components/testcomp' In the export default{} section, I included the component as follows: components:{ 'testcomp&apo ...

Attempting to retrieve data from cloud Firestore utilizing keyvalue in Angular

My database stores user information under the 'users' collection. I can access this data using the following code: In my service: users$ = this.afs.collection<Users[]>('users').valueChanges(); In my component: public users = t ...

Error 403 Forbidden on Selenium grid due to proxy issue

While I have been conducting website tests using Selenium webdriver on my local machine, I now aim to perform these tasks on a Windows EC2 instance. After researching, I discovered that Selenium Grid2 can be utilized on EC2 servers. However, upon setting u ...

Presenting XML data on a webpage using AJAX technology

I am currently working on setting up a web radio station with a program that allows streaming (jazler) to send xml files via ftp to a web server to automatically update information such as the current song playing and previous songs. The code for NowOnAir ...

I am having trouble formatting dates using the Moment.js library on Internet Explorer, it keeps returning

When using the moment.js date library to format a date, I encountered an issue on IE where I would get NaN in the output. This problem did not occur on other browsers such as Chrome and Firefox. var value = "2015-11"; moment(value).format("YYYY-DD-01 00: ...

The list of lists is giving an error: "Cannot read property 'name' of undefined."

What am I doing wrong here? let items = [{ name: 'client1' }, { name: 'client2' }, { name: "client3"}]; for (let i = 0; i < items.length; i++) { if (items[i]['name'].includes(self.autocomplete)) { self.box += '<l ...

Allow users to upload .gltf or .glb 3D models using three.js

Greetings! I have recently embarked on the journey of learning about three.js I am curious to know if there is a way for the user to upload their .glb / .gltf 3d model and view it instantly on the canvas? My thoughts are leaning towards utilizing PHP, es ...

Regular expression to enclose non-quoted values (numbers and boolean) within quotes

I have a JSON file that is valid, but I need to add quotes around the number values and boolean values in order to send this JSON to a wix repeater that requires quotes around them. If anyone can assist me with this, I would greatly appreciate it. Exampl ...