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

When using MathJax on an iPhone with a device width setting, you will experience the

Utilizing MathJax to display mathematical symbols on a mobile device- such as an iPhone, I encountered an issue with the meta tag: <meta name="viewport" content="user-scalable=no, width=device-width" /> This seemed to be causing problems as the Mat ...

Stop the duplication of downloading JavaScript files

When it comes to my website, I have incorporated sliders that stream videos from Vimeo. Upon running a check on GTMetrix, I noticed an overwhelming number of http requests. Looking at the waterfall, I discovered numerous duplicate downloads of javascript, ...

Integrating external JavaScript widgets into the web application in real-time

I am currently engaged in a React js project that involves the dynamic addition of third party scripts (widgets) to the web app. These widgets encompass various third party platforms such as Twitter, Instagram, Youplay, Youtube, and more. The existing co ...

JavaScript mouse and touch movement events (mousemove, pointermove, touchmove) are not always accurate

I'm currently working on developing a JavaScript whiteboard and have implemented the following code: let lastTimestamp = 0; const fps = 1000/60; document.addEventListener("pointermove", moveMouse, false); function moveMouse (e) { e.preve ...

Getting the response from Google Cloud Translate API using Node JS

Recently, I've been experimenting with the Google Cloud Translate API in NodeJS. While I am able to successfully console.log the value returned from a promise, I am facing challenges passing that value into an EJS template file. Whenever I try to disp ...

Is there an Angular directive that can replicate a mouseenter event?

Is there a way to simulate a mouseenter event with a directive? I have been searching for a directive that can simulate a mouseenter event, but all I have found so far is one that binds a function to mouse over or karma tests for simulating mouse over. W ...

Create a CSS menu that remains fixed at the top of the page and highlights the current submenu as

When explaining a concept, I find it easier to include a drawing to ensure clarity. https://i.stack.imgur.com/IChFy.png My goal is to keep the menu at the top of the page after scrolling past the header. https://i.stack.imgur.com/3fzJ6.png Using Bootst ...

Attempting to follow along with a guide to create a Spring Boot Vue.js project, encountering a few errors along the way

I am currently following a tutorial on building a Spring Boot project with Vue.js from this GitHub page. I have successfully created an empty Vue project using the command vue create frontend --no-git and proceeded until the step where it says: "Calling a ...

Leveraging Techniques within Computed Attributes using stored values in Vuex

I've been working with Vuex and I'm facing a challenge where I need to utilize methods within a computed property, similar to what I have set up in my actual project. However, I'm struggling to understand how to invoke the method and store t ...

Teaching sessions along with the implementation of functions

I've created a set of input fields with the class replaceInput. The idea is to have a simple function that clears the value when the user focuses on the field, and then returns it to 'X' if the field is empty on focus out. My query is, coul ...

Struggling with navigating JSON data in JavaScript and facing difficulties sorting the array

I am currently facing the challenge of organizing data obtained from an API using JavaScript. JavaScript Code to Retrieve Data: function getResults() { var url = $.getJSON("http://api.api.com&leagues=SOCENGPRE&lang=en&format=jsonp&cal ...

How to Implement Snap-Enabled Dragging in a Container Using jQuery UI

Issue Description (Fiddle): I am using the jQuery UI's .draggable() function to make the red element snap inside the blue container. However, it is snapping to one edge only instead of completely fitting inside (both edges). It requires further dragg ...

Pressing the Like Button triggers the transfer of a specific variable from PHP to jQuery

I have a piece of PHP code that I am using to display all users' posts, each with its own unique 'like' button: $sql = "SELECT * FROM posts"; $result = mysqli_query($con,$sql); while($row=mysqli_fetch_assoc($result)){ $post_content = $ro ...

"Learn how to use jQuery to retrieve a specific row from an HTML table based on equality with a certain

I have a dynamically generated table using PHP. The information in this table is related to different semesters (such as first, second, third, etc.). I want to display specific semester information when a user clicks a link from the same table without need ...

What distinguishes {key:" "} from {key:" "}, when it comes to JSON files?

I have been working on implementing validation using express Router. The issue I encountered is that when I pass {title:""}, the express-validator does not throw an error. However, when I pass {title:" "}, it works properly. exports.postValidatorCheck = [ ...

How should one go about creating and revoking a blob in React's useEffect function?

Consider this scenario: import { useEffect, useState, type ReactElement } from 'react'; async function getImage(): Promise<Blob> { // Some random async code const res = await fetch('https://picsum.photos/200'); const blob = ...

Having trouble getting an HTML form to function with Ajax and PHP?

Seeking assistance from anyone who can lend a hand. I am delving into the complexities of Ajax, and I'm encountering issues where it seems like the script is being completely ignored or perhaps I'm just making a rookie mistake. Prior to display ...

Code not functioning properly in Internet Explorer

In one of my JavaScript functions, I have the following CSS line which works well in all browsers except for IE (Internet Explorer). When the page loads, the height of the element is only about 4px. element.setAttribute('style', "height: 15px;") ...

Unable to access the attributes of the mongoose model

I'm experiencing an issue with my mongoose model.find code below Displayed here is my node.js code that utilizes mongoose to interact with MongoDB. However, upon running it, I encounter the following error message: Starting... (node:7863) Unhandl ...

Getting the most out of fonts with Webpack sass-loader

I recently set up a custom font in my project like this: $font-path: '~@/assets/fonts/'; @font-face { font-family: 'mainFont'; font-weight: 300; font-style: normal; src: url('#{$font-path}mainFont/mainFont.eot&apos ...