Vue component not displaying object property

I am currently working on implementing a filter method in a Vue component.

Here is the filter method I am trying to use:


filterHotels:function(){

    var thisHotels = this.hotelRoomArr;

    console.log(this.hotelRoomArr['107572']['rooms'])

    //this outputs:

    {__ob__: Observer}
    3: (...)
    __ob__: Observer {value: {…}, dep: Dep, vmCount: 0}
    get 3: ƒ reactiveGetter()
    set 3: ƒ reactiveSetter(newVal)
    __proto__: Object


    thisHotels['107572']['rooms'] = {};

    console.log(this.hotelRoomArr['107572']['rooms']);

    //this outputs:

    {__ob__: Observer}
    __ob__: Observer {value: {…}, dep: Dep, vmCount: 0}
    __proto__: Object
}

Upon inspecting the code above:

Despite setting the rooms property of thisHotels to an empty object, it seems that the rooms property of this.hotelRoomArr also gets modified.

Logically speaking, the rooms property of this.hotelRoomArr should not be affected by this change.

What can I do to prevent changes to this.hotelRoomArr when modifying rooms?

Answer №1

By assigning this.hotelRoomArr to thisHotels, thisHotels now holds a reference.

To avoid this, consider using the cloneDeep function from the lodash library:

https://lodash.com/docs/4.17.15#cloneDeep

import cloneDeep from 'lodash/cloneDeep';

...

var thisHotels = cloneDeep(this.hotelRoomArr);

Using cloneDeep creates a separate copy and ensures that modifications do not affect the original this.hotelRoomArr

Answer №2

One possible explanation for this behavior is that by assigning thisHotels = this.hotelRoomArr;, you are essentially creating a reference to the original object.

Any changes made to thisHotels will also affect this.hotelRoomArr due to their shared reference.

If you want an independent copy of the object, you can achieve this by using JSON methods as follows:

let thisHotels = JSON.parse(JSON.stringify(this.hotelRoomArr))

Personally, I prefer using the JSON object method for making non-reference copies.

Answer №3

To resolve the problem, consider using the spread operator when defining the local variable thisHotels by spreading the hotelRoomArr array instead of simply assigning it.

//initial code snippet
let thisHotels = [...this.hotelRoomArr]
//additional code goes here

PS: It is recommended to use let instead of var for better scope management.

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

While troubleshooting the app, I encountered an error that says: "The property 'answers' cannot be read as it is undefined."

Everything was going smoothly with my app until it suddenly crashed, displaying the error message "Cannot read property 'answers' of undefined". Let's take a look at the specific piece of code causing the issue: function mapStateToProps({ ...

Discovering the property name of an object in Angular using $watch

Is there a way to monitor an object for changes in any of its properties, and retrieve the name of the property that changed (excluding newValue and oldValue)? Can this be accomplished? ...

Exploring the contrast between 'completed' and 'upcoming' in callback functions within node.js

Within the passport documentation for authentication configuration, there is a function that appears rather intimidating as it utilizes the enigmatic function "done." passport.use(new LocalStrategy( function(username, password, done) { User.findOne( ...

Uncovering the Model within a controller in Ember JS

I am attempting to extract the original model object from a controller for the purpose of persistence (without utilizing ember-data). The straightforward approach would be: controller.get('content'); However, this method is not effective. The i ...

Is it necessary to alter the number of rows or columns in the table?

I'm having an issue with my code where the table is not changing the number of rows based on the selected input option. It seems to only read the first value of the select id and does not update the rows accordingly. Can someone help me identify the m ...

inputting an array of strings into the value attribute of an input element using jQuery

Whenever a user writes something in the input field with id="clientAdd" and presses enter, that text should be displayed as a tag inside a div. These tags are then saved as an array of strings, which I want to pass as the value for the hidden input field w ...

What is the process of transferring a file to the server side as byte code in Vue.js?

My current challenge involves transferring an attached file from the client-side to the server-side. I have attempted a couple of methods to retrieve the file, as outlined below: 1) var files = event.target.files; var file = files[0]; 2) var image ...

Is it possible for JavaScript to identify modifications in the HTML, like an input made with Ctrl+Shift+I?

Check out this website I'm currently working on. As a fun challenge for users, we're encouraging them to use ctrl+shift+i to manipulate the HTML and modify certain elements. Is it possible for Javascript or CSS/HTML to detect these changes? For ...

The resolveMX function in Google Cloud Functions is encountering issues when trying to process a list of domains

Here is the task at hand. I have a large list of domains, over 100,000 in total, and I need to iterate through them using a foreach loop to resolve MX records for each domain. Once resolved, I then save the MX records into another database. Below is the c ...

Is there a way to update the href attribute within the script section in vue.js?

I need to dynamically set the href attribute of a link based on data retrieved from a database and rendered in the methods section. <template v-if="header.value == 'ApplicationName'"> <a id="url" href="#" target="_blan ...

React Native: Struggling with Button Styling

I am relatively new to React Native, although I have experience with React in my professional work. I'm finding that applying styles to components in React Native is a bit different than what I'm used to. Specifically, I am struggling to apply s ...

Experiencing a 404 ERROR while attempting to submit an API POST request for a Hubspot form within a Next.js application

Currently, I am in the process of developing a Hubspot email submission form using nextjs and typescript. However, I am encountering a couple of errors that I need help with. The first error pertains to my 'response' constant, which is declared b ...

"Utilize TipTap with the power of your personalized name

Is it feasible to work around the inability to use the name tag on TipTap for sending data through forms in Laravel? Here's an example of what I have in mind: <tiptap-vuetify v-model="content" :extensions="extensions" ...

Experiencing challenges accessing information from the useEffect hook in React

I'm facing some issues with my useEffect hook and I can't seem to figure out why it's not working. I've been trying to make a call to an endpoint, but it seems like I'm not getting any response back. Any help would be greatly appr ...

I can view the data retrieved in the console, but I am having difficulty displaying it on the screen

I have successfully retrieved data from the API, as indicated by the output in my console. However, I am facing issues in displaying this data on the webpage due to a potential error in my code structure. Despite this, I can confirm that the fetched data ...

Tips for adjusting image and div sizes dynamically according to the window size

In my quest, the end goal is to craft a simplistic gallery that closely resembles this particular example: EXAMPLE: This sample gallery is created using Flash technology, but I aim to develop mine utilizing HTML, CSS & Javascript to ensure compatibil ...

Utilizing ng-repeat to display a collection of Angular Highcharts charts

As I work on developing a KPI app using Angular JS, my goal is to establish a collection of charts. Each item in the list will display distinct values and feature a different chart type based on my Model. I am relying on the highcharts-ng directive for th ...

The function $http.get in AngularJS is providing an undefined response

In the process of developing a small Angular application, I started with this seed project: https://github.com/angular/angular-seed. The only modifications I made were to the following files: /app/view1/view1.js 'use strict'; angular.mod ...

Seamless side-to-side navigation

Currently, I am working on a website that has horizontal overflow instead of the common vertical scroll. While everything seems to be functioning properly, I need to enhance the user experience by adjusting the amount scrolled to move larger sections of th ...

What is the most efficient way to align a localStorage variable with its corresponding page?

In my current project, I have developed a component that is utilized in an online science lab setting. To ensure continuity for researchers who navigate away from the page and return later, I have integrated the use of localStorage. The goal is to preserv ...