Sending an incorrect value to the data variable

Apologies for my limited proficiency in English, Hello, I am new to Vue and struggling with an issue that I can't seem to resolve. I am fetching art data from an API (a simple list of dictionaries), and then creating a multi-array structure (list of lists) by saving the raw response.data and my multi-array in the data variable of the Vue instance. Despite having similar data, the source list remains unchanged:

https://i.stack.imgur.com/wc6cV.png https://i.stack.imgur.com/QHNID.png

The fields offsetX and offsetY shouldn't exist in the raw variable. Additionally, the field height seems to be incorrect as well. These unexpected fields are also present in the raw variable, and I'm unsure why. Below is the code snippet of my application:

$(document).ready(function () {

    var app = new Vue({
        el: '#app',
        data: {
            raw: null,
            info: null,
            art_width: 252,
            window_width: null,
            window_height: null,
        },
        mounted() {
            this.window_width = window.innerWidth
            this.window_height = window.innerHeight 
            axios({
                method: 'get',
                url: '/content/art',
                contentType: 'application/json'
            })
            .then(function (response) {
                app.raw = response.data.items.slice();
                // If I remove create_array function from app, raw variable behaves normally
                app.info = create_array(app.raw)
            });
            window.addEventListener('resize', () => {
                if (app.raw !== null){
                    app.info = create_array(app.raw)
                    this.window_width = window.innerWidth
                    this.window_height = window.innerHeight 
                }
            });
        },
        computed: {
            arts_in_line () {
                return parseInt((this.window_width - 24*2) / (this.art_width+10));
            },
            center_div_width ()  {
                return this.arts_in_line * (this.art_width + 10)
            }
        }
    })

});


function create_array(info) {
    // Calculate number of arts in each line
    arts_in_line = parseInt((window.innerWidth - 24*2) / (252+10));
    // Initialize the multi_array to store the arrays
    var multi_array = [];
    // Build the multi-dimensional array
    for (var index = 0; index < info.length; index = index + arts_in_line) {
        multi_array.push(info.slice(index, index+arts_in_line));
    }
    // Store vertical offsets
    var top_offset = []
    for (var row = 0; row < multi_array.length; row ++) {
        for (var col = 0; col < multi_array[row].length; col ++) {
            // Get the scale of art
            let scale = 252 / multi_array[row][col]['width'];
            // Calculate new height and offsetX/Y values
            if (row == 0) {
                top_offset[col] = parseInt(multi_array[row][col]['height'] * scale) + 10;
                multi_array[row][col]['offsetY'] = 0;
                multi_array[row][col]['offsetX'] = (252+10) * col + 'px';
                multi_array[row][col]['height'] = multi_array[row][col]['height'] * scale + 'px';
                multi_array[row][col]['width'] = 252 + 'px';
            } 
            else {
                multi_array[row][col]['offsetY'] = top_offset[col] + 'px';
                top_offset[col] = top_offset[col] + parseInt(multi_array[row][col]['height'] * scale) + 10;
                multi_array[row][col]['offsetX'] = (252+10) * col + 'px';
                multi_array[row][col]['height'] = multi_array[row][col]['height'] * scale + 'px';
                multi_array[row][col]['width'] = 252 + 'px';
            }
        }
    }
    return multi_array;
}

Answer №1

Instead of using a loop to create a multi-dimensional array like this:

// Create mulri array
for (var index = 0; index < info.length; index = index + arts_in_line) {
    multi_array.push(info.slice(index, index+arts_in_line));
}

You can simplify the process by creating a new array multi_array and iterating through info to add elements directly to it. For instance:

var multi_array = [];
// Save vertical offsets
var top_offset = []
for (var row = 0; row < info.length; row ++) {
    for (var col = 0; col < info[row].length; col ++) {
         let scale = 252 / parseInt(info[row][col]['width']);

         const temp = {
            id: info[row][col]['id'],
            // Additional values you want
            height: (parseInt(multi_array[row][col]['height']) * scale) + 'px'
         }

         multi_array[row][col] = temp
    }
}

return multi_array;

This approach gives you flexibility to include or exclude any key you desire in your new array.

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

Could this be considered a typical trend - opting to return data instead of a promise?

I recently came across a new approach while reading 'Mean Machine'. Typically, I have always been taught to return a promise from a service to the controller and then handle it using .success or .then. In this case, the author is directly retur ...

Strategies for spreading a mode to the composite component within VueJS

When it comes to the Vuetify text field component, there are numerous options available for customization. One idea is to create a custom text field component with predefined options such as icons, flat design, or boxed layout. However, I want to avoid man ...

Steps for clearing input field with type=date in Protractor:

I am currently working with protractor version 4.0.4 and I'm encountering an issue where I cannot clear a date input field. It seems like Chrome is introducing some extra controls that are causing interference. You can find further details about Chro ...

Is there a way to transform a tabulated tree into JSON using JavaScript?

I've been searching for a solution, but I have come to the conclusion that this question is quite peculiar. How can I convert the following text file using tabs for spacing: parent child child parent child grandchild grand ...

Creating a function for loading dynamic content in XSLT can be achieved by following these steps

When I call the function collapseandexpand() for static elements only, it does not work. Now, how can I create the same function to handle dynamic content in xslt? Javascript Code: <script language="javascript" type="text/javascript> <xsl:text&g ...

Is it possible to reposition the vertical scrollbar to a location that is not on the left or right side?

Whenever I resize my modal on small screens, a horizontal scrollbar appears, causing the vertical scrollbar to disappear as it gets stuck on the right side. I am looking for a solution to keep the vertical scrollbar on the right side of the modal while scr ...

Update all field values in Redux-form version 6.0 and above

I am attempting to update several values in redux-form. They are stored in a single object, and I want to replace the current redux-form state values with those from my object. One method I have tried involves using this.props.reset() followed by multipl ...

Insert a scrollbar into the new popup window on Internet Explorer after the window has been opened

I am looking to enable scrolling in a pop-up window after it has been opened. While FireFox offers the 'window.scrollbars' property for this, Internet Explorer does not have a similar feature. Is there a way to add scrolling functionality in IE u ...

Experimenting with the speechSynthesis API within an iOS webview application

I'm currently working on developing an app that features TTS capabilities. Within my webview app (utilizing a React frontend compiled with Cordova, but considering transitioning to React Native), I am implementing the speechSynthesis API. It function ...

Out of nowhere, while trying to update the app's packages with npm install, I encounter the following unexpected error

Error in module exports due to unexpected identifier. SyntaxError: Unexpected identifier > at Object.exports.runInThisContext (vm.js:76:16) > at Module.\_compile (module.js:542:28) > at Object.Module.\_extensions..js (module.js: ...

jQuery Ajax Redirect Form

I am currently developing an HTML application with a form. Upon clicking the submit button, I initiate a server-side call using jquery.ajax(). However, when the server returns an exception, such as a Status Code 500, I need to display an error message on t ...

React Issue: Make sure to assign a unique "key" prop to each child element within a mapped list

I encountered the error message below: react Each child in a list should have a unique "key" prop. Here is my parent component code snippet: {data.products .slice(4, 9) .map( ({ onSale, ...

Capture a fragment of a scene and convert it into a unique texture using THREE.JS

I'm interested in creating a texture of a specific area in my scene, similar to the example shown in the official documentation for three.js framebuffer here. As I examine the code provided, there's one particular aspect that's unclear to me ...

Set the value of a hidden field and proceed to submit it in CodeIgniter

I seem to be struggling with a simple task of setting a hidden input value. Here is how my form is structured: <?php echo validation_errors(); ?> <?php echo form_open('purchasing'); ?> <h1>Purchasing Re ...

In Vue 3, the old and new values returned by a deep watcher are consistently the same

const app = { data(){ return { form: { name: '', password: '' } } }, watch: { form: { handler(form, oldForm){ console.log(form, oldForm); }, deep: true } } ...

Error encountered during Nuxt build: Syntax error on Line 1 of the SCSS component file

I'm currently working on a project in node 18.7.0 that utilizes nuxt 2.15.8. Within my Vue component, I have the following SCSS code: <style lang="scss"> .Accordion { --Accordion__margin-top: 2.5rem; &__items { margin ...

Capturing C# log data for JavaScript interactions

Can anyone provide recommendations on how to capture JavaScript interactions in a browser using C#? I am interested in developing a web crawler that can track these interactions, allowing me to search for potentially harmful calls. ...

Preserving the true IP address when initiating cross-domain requests

Initially, I tried creating a reverse proxy using Express to enable forwarding requests from localhost:3000/request to somesite.com/request. Here is the code snippet I used: var request = require('request'); app.get('/', function(req, ...

Using AngularJS to chain promises

After coming across some advice on AngularJS validation and promises, I am interested in creating a chain of confirmation dialogs to validate multiple steps at once. By making an API call based on user input, we can determine what steps require confirmati ...

Retrieve pixel information upon touch in an Appcelerator Titanium application on Android or iPhone

Can pixel level data of an image view be accessed using Titanium Mobile on Android/iPhone? ...