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

Enable Sound when Hovering over Video in React Next.js

I am currently facing an issue while trying to incorporate a short video within my nextjs page using the HTML tag. The video starts off muted and I want it to play sound when hovered over. Despite my best efforts, I can't seem to get it working prope ...

Utilize a for loop in Vue.js to save a fresh array of objects in a structured format

Trying to achieve the following using Vue: I have two JSON objects that provide information on languages and the number of inputs per language. Using nested loops, I display all the inputs. My goal is to create an object for each input with additional det ...

Incorporating Checkbox Value into Textbox with classic ASP and jQuery

Here is a glimpse of the code I've written: response.write "<th align=left><font size=2>" response.write "1. <input type=checkbox class='checkboxes' value='ORG'>Organization" response.write "</font> ...

How can you use jQuery.ajax to solely fetch the status code without downloading the entire document?

My application relies on the use of jQuery.ajax to check if a particular resource exists by constantly polling it. Once the resource is no longer returning a 404 status code, the app redirects to view that resource. However, I am concerned about downloadin ...

Deactivate the other RadioButtons within an Asp.net RadioButtonList when one of them is chosen

Is there a way to disable other asp.net radio buttons when one of them is selected? I have three radio buttons, and I want to disable the other two when one is selected. After doing some research, I managed to disable the other two when the third one is se ...

Incorporating and retrieving JSON data saved within vuex storage

I am working with a vuex store to add JSON data in the following format: [ { "id":1, "firstname": "toto", "lastname": "titi" }, { "id":2, "firstn ...

AngularJS: default option not being selected in dropdown menus

I need assistance with a dropdown list issue. See the code snippet below: My Controller (function(angular) { 'use strict'; angular.module('ngrepeatSelect', []) .controller('ExampleController', ['$scope', functi ...

Older versions of Android, specifically Android 7 or lower, seem to encounter issues with Apis in React Native when utilizing axios. Fortunately, this problem doesn

For fetching the data, I utilized the 'axios' library. Surprisingly, it works flawlessly on newer Android devices (specifically Android 9 and 10). However, when it comes to older devices like Android 7 or earlier, a persistent Network Error occur ...

Is there a way to redirect using Express JS when the destination is

Hello there, I'm encountering an issue with redirecting in express js. I have a function that should trigger when a submit button is pressed and then redirect to a different page. However, when using res.redirect('/results.ejs');, I receive ...

Encountering an Error in Node.js When Defining Routes Using Variable Routes

Here is the code snippet from my App.js file- var routes = require('./routes'); app.get('/', routes.index); //var abt = require('./routes/about'); app.get('/about', routes.about); This is the code from my index.j ...

Issues with clickable links within a table cell

I am facing an issue with a table where rows <tr> are generated dynamically by a PHP loop. I have transformed the entire row into a link, but the problem arises when there is an <input type="checkbox"> within the row. Whenever I check the check ...

What is the best way to import API Endpoints from various directories in an Express Server?

I have been using a script to load my API endpoints like this: readdirSync('./routes/api').map((r) => app.use( `/api/v1/${r.split('.')[0]}`, require(`./routes/api/${r.split('.')[0]}`) ) ); This script reads eve ...

What is the best way to organize Node/Express routes based on their type into different files?

My /router/index.js file is becoming too cluttered, and I want to organize my routes by group (user routes, post routes, gear routes) into separate files within /router/routes/. Here's what I currently have set up: app.js var express = require(&apos ...

Organize the HTML output generated by a PHP array

There must be a simple solution to this, but for some reason, it's escaping me right now. I've created custom HTML/CSS/JS for a slider that fetches its content from an array structured like this: $slides = [ [ 'img' = ...

Creating evenly spaced PHP-generated divs without utilizing flexbox

My goal is to display images randomly from my image file using PHP, which is working fine. However, I am facing an issue with spacing the images evenly to fill the width of my site. This is how it currently appears: https://i.stack.imgur.com/AzKTK.png I ...

Retrieve the component instance from a Vue watcher

I'm currently developing a project that acts as a bill manager and I am looking to have the subtotal recalculated automatically whenever the quantity or unit value changes. I've tried using watchers and computed properties to achieve this but hav ...

Pressing the enter key does not submit the Vue.js form

When attempting to submit the form by pressing "enter" on the keyboard, it only works when I click the "submit" button. I made sure to add @submit to the form event to ensure it triggers, but upon checking a log, I found that it only triggers when clicking ...

As I embarked on my journey into node.js, I encountered some stumbling blocks in the form of errors - specifically, "Uncaught ReferenceError: module is not defined"

Embarking on my Node.js journey, I am delving into the world of modules. After ensuring that both node and npm are correctly installed, I will share the code below to provide insight into the issue at hand. Within my project, I have two JavaScript files - ...

The full screen menu is exclusively displayed in the navigation bar

My HTML and CSS code is causing an issue where the full-screen menu only appears in the nav bar. This problem seems to be specific to Safari. To solve the issue, I need to remove the following code: .nav { position: fixed; } However, I still ...

Using Javascript, Google Charts is able to interpret JSON data

I am currently working on integrating Google Charts and populating it with data from an external JSON file that I have generated using PHP's json_encode() function. After some effort, I managed to get Google Charts to display data successfully, but f ...