JavaScript, specifically in the VueJS framework, consistently defaults to utilizing the final value within a

Describing my issue, I am using a for loop to extract elements from an array and assign them to a JSON value. It looks something like this:

hotel={ rooms: 2, price: [ 100, 200 ], occupation: [ '1 child', '1 adult' ]

I aim to push this data into an array of JSONs:

hotels = [ { rooms:1, price: 100, occupation: '1 child' },... ]

This is what I have tried:

var json = { rooms : 1, price:null, occupation:null }    
for (let i=0 ; i < hotel.rooms ; i++){
    json.price = hotel.price[i]
    json.occupation = hotel.occupation[i]
    this.hotels.push(json)
}

However, the array hotels always ends up with the last values from the loop. I attempted handling this using try {throw i} catch(ii) {...}, but it did not work as expected.

Answer №1

The issue stems from the fact that each element within the array this.hotels is merely a reference to the same underlying json object. Consequently, any mutation applied to this object will be reflected across all elements in the array. This results in each element ultimately containing the same data.

To resolve this issue, it is recommended to push a new "copy" of the object instead. By creating a distinct copy, you can safeguard against unintended mutations affecting other array elements. One approach involves utilizing object spread notation:

this.hotels.push({...json});

An alternative method is to employ Object.assign({}, json) in place of the spread notation. Another option is to retain your existing code structure but move the declaration var json = {...} inside the loop. Furthermore, replacing var with let ensures that a new local variable is created for each iteration, preventing continual global mutations. There are various solutions available to address this issue.

Answer №2

When working with objects, it is important to remember that they are reference types. This means that each time you push to the hotels array, you need to create a new object.

To address this issue, there are a couple of simple solutions:

You can use object literals in the push method like this:

this.hotel.push({ rooms: 1, price: hotel.price[i], occupation: hotel.occupation[i]})

Alternatively, you can move the variable declaration into your loop as shown here:

var json = { rooms : 1, price:null, occupation:null }

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

Creating a Typescript type for the react-intl component within a single file

Currently, I'm trying to incorporate the injectIntl component directly in the file instead of using the traditional export default injectIntl(Component). However, I am encountering difficulties when it comes to typing the component. This is a snippet ...

Variability in Swagger parameter declaration

Is it possible to specify input parameters in Swagger with multiple types? For example: Consider an API that addresses resources using the URL http://localhost/tasks/{taskId}. However, each task contains both an integer ID and a string UUID. I would like ...

Copying specific cell values from a column in Pandas when certain conditions are satisfied

In order to create a new column C based on specific conditions in columns A and B, I need to copy a cell value from column B. The conditions are as follows: Copy the cell value in column B whenever "Forward" changes to either "Stop" or "Backward" Copy the ...

Transmit specific elements from an array to another array exclusively with Javascript

I have some data stored in a JSON array like this: source=[{"OperationName":"All","PrivilegeName":"Roles CRUD"}, {"OperationName":"Read","PrivilegeName":"Roles Read Delete"}, {"OperationName":"Delete","PrivilegeName":"Roles Read Delete"}, ...

Enhance the functionality of selectize.js by incorporating select options through ajax

I'm currently working on implementing options to a select box using AJAX and selectize.js. When not using selectize.js, everything functions correctly. The two select boxes are interconnected so that when one is updated, the values in the other select ...

Creating a JavaScript array in Rails 4 based on current data without the need to reload the webpage

Currently in my rails 4 app, I am working on a unique tags validation using jquery validate to ensure that tags are not duplicated before they can be added to an item. The tag list structure is as follows: <div id="taglist"> <span class="label ...

How to eliminate excess white space on the right side in Bootstrap 4

Could someone please clarify why I am experiencing a white space on the right side when using Bootstrap 4? This is the primary code block for the page. <main id="intro" role="intro" class="inner text-center"> <h2>Lorem Ipsum</h2> ...

Elevate the element from the choice API to the organization API using this.$parent

I recently developed a Vue 3 component called "Tab" using the option API. Here is the code: export default { name: "Tab", props: { name: {required: true}, iconClass: {required: true}, selected: {default: false} }, da ...

Looping through a PHP foreach function, assigning a distinct identifier for the select element using getElementById

My goal is to extract the price value, $option_value['price'], from a dropdown menu as a string rather than using .value, which fetches something different. I am working with select menus generated in a foreach() loop. Each dropdown menu contain ...

Ways to turn off default browser tooltip using bootstrap4 tooltip

Check out the code below, which demonstrates displaying both the bootstrap tooltip and the native title-attribute tooltip: This is an example of text with a tooltip using Font Awesome icon: <i class="far fa-question-circle" data-toggle="tooltip" title= ...

Is the value of the incorrect store ref in Vue3 being altered?

Welcome to the store: import { ref } from "vue"; // Storing all the country data export const countriesData = ref(); export const isLoading = ref(true); async function fetchData() { try { isLoading.value = true; const respon ...

What is the method for showing a JavaScript variable in a popup window?

I am having an issue with a search form that is supposed to display a list of persons based on filters. Once the search results are shown, I want a link (id=names_list) that, when clicked, will open a dialog box containing the names of the persons. I have ...

Utilize separate environment variables for distinct environments within a React project

Is there a secure method to externalize all environment variables, including secret keys, for a React application within a DevOps setup? Our goal is to streamline the build process across different environments, each with its own unique set of environment ...

Adding local JavaScript to a Vue component is a great way to enhance its functionality

I am currently working on integrating a homepage concept (Home.vue) into my project. The design is based on a template that I purchased, which includes CSS, HTML files, and custom JavaScript. While most of the CSS has been successfully imported, I am havin ...

Append a constant string to the conclusion of the route parameter

Using React Router v6.4.1, I am aiming for a consistent conclusion to a series of dynamic routes. Specifically, I want my product detail routes to always end with "-product". For example, if the path is "/shaver-900-product", it should activate my Produc ...

Hiding a related field using a designated delimiter can be achieved with JavaScript

I am looking to create a function that hides the corresponding textarea field of a dropdown. This functionality will be utilized in multiple instances, hence the need for it to be within a function. <div id="formElement1" class="field"> <labe ...

If the SASS condition matches the variable for the background color, then

I attempted to create a conditional statement in my component using Sass @if and @else. The condition I set was that if background == var(--bg-danger), the color should be white. However, it only returned white and did not trigger the else condition. @mixi ...

Displaying a div component in React and Typescript upon clicking an element

I've been working on a to-do list project using React and TypeScript. In order to display my completed tasks, I have added a "done" button to the DOM that triggers a function when clicked. Initially, I attempted to use a useState hook in the function ...

The code functions properly on React Webpack when running on localhost, however, it fails to work once deployed to AWS Amplify

As I work on my React.js app, I encountered an issue with hosting pdf files on Amplify. While everything runs smoothly on localhost/3000, allowing me to access and view the pdf files as desired either in a new tab or embedded with html, the same cannot be ...

The CORS middleware seems to be ineffective when used in the context of Node.js

I have set up my REST API on a Raspberry Pi server and connected it to the public using localtunnel. I am trying to access this API from a localhost Node.js application. The Node application is running on Express and includes some static JS files. However, ...