What is the best way to iterate through an object and retrieve the following 3 items using a for loop in JavaScript

After fetching data from a website and storing it in a variable, I have successfully implemented a for loop that returns 3 properties from the object every time a button is clicked.

However, the issue arises as the same data is returned with each button click. I am unsure of how to adjust the for loop to start from a specific object.

data: {
    fetched_list: [],   // holds fetched data
    list: [],          // empty list for future objects
    list_key: '0'     // last loop index
},

requestInformation(){
  const temp = [];
  for (let i = 0; i < 3; i++){
    temp.push(this.fetched_list[i]);
  }
  this.list = this.list.concat(temp); 
}

I am struggling to figure out how to make the for loop start at the next 3 objects when the button is clicked.

My attempt to save the last i number in list_key did not yield a solution on how to fetch the subsequent 3 properties.

For reference, you can view the problem here: https://jsfiddle.net/auq7wzuc/

Answer №1

There are a few adjustments that must be made.

Take a look at this improved version: https://jsfiddle.net/auq7wzuc/6/

In essence, the line below needs to be updated:

this.recipe.list_key = this.recipe.list_key++;

This code will not increment the value as intended-- it will remain at zero. To increase by 3, we should use:

this.recipe.list_key += 3;

Additionally, we should adjust the parameters of the for loop to stop not at 3, but at 3 more than the initial value.

Answer №2

Noticed a flaw in the way you increment this.recipe.list_key and your comparison of i < 3 in the for loop. I have made some adjustments to correct this issue. Please review the modified code below. Hopefully, this resolves the problem.

In addition, I have also adjusted the initial value of list_key from character '0' to integer 0 to address potential concatenation versus addition concerns in JavaScript.

new Vue({
    el: '#app',
    data: {
        recipe: {
            fetched_list: [],
            list: [],
            list_key: 0
        }
    },
    methods: {
    requestInformation(){
      const temp = [];
      console.log(this.recipe.list_key);
      var end = this.recipe.list_key + 3;
      for (let i = this.recipe.list_key; i < end ; i++){
        temp.push(this.recipe.fetched_list[i]);
      }
      this.recipe.list_key += 3;
      this.recipe.list = this.recipe.list.concat(temp);
    }
    },
    created(){
        axios.get('https://hn.algolia.com/api/v1/search_by_date?tags=story').then(({data}) => this.recipe.fetched_list = data.hits);  
    }
});

Feel free to ask if you have any doubts or need further clarification.

Answer №3

content: {
    meal: {
        selected_ingredients: [],
    recipe_list: [],
        list_index: 0
    }
},
actions: {
 gatherData() {
  this.meal.recipe_list = this.meal.selected_ingredients
    .slice(0, this.meal.list_index += 3)
    .map(ingredient => ingredient);
 }
}

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

Transferring data from AJAX to PHP class methods

Q. Is it feasible to transfer data from ajax to a specific php class with functions? For instance, verifying a username on the registration form to check if the user already exists. This form is straightforward and will gather a username input along with ...

How come the HTML page served by the express.js route isn't linked to a CSS stylesheet?

Recently, I've been working with a server.js file that imports a router const path = require("path"); const express = require("express"); const app = express(); const PORT = 8080; app.use(express.urlencoded({ extended: true })); app.use(express.jso ...

Exploring JqueryUI tab navigation with the help of the <a> tag

I have come across several articles mentioning the possibility of navigating JqueryUI tabs using a button or anchor tag. Here is the method I am currently using: $("#vtabs").tabs(); $("#tabsinner").tabs(); $(".changeTab").click(function() { alert("as ...

Utilizing the sAjaxSource property in Datatables to fetch data through Ajax from multiple tables while dynamically passing arguments

I am facing an issue with populating two datatables using data retrieved from a flask API through a GET request. My data source URL is localhost:5000/data, but for some reason, I am unable to display the data in the datatables. Interestingly, when I use a ...

Selenium - How to pass a file path to a dynamically generated input element that is not visible in the DOM

Check out this example of HTML code: This is how you create a visible button and display the selected file: <button id="visible-btn">visible button</button> <p>selected file is: <span id="selected-file"></spa ...

An array of memory addresses containing strings in the C programming language

Just starting out with C language and I've been struggling with pointers. Could really use some assistance. Thank you in advance! Check out this code snippet: char *a[2]; a[0] = "blah"; a[1] = "hmm"; printf("%s %d\n", a[0],a[0]); printf("%s %d& ...

The React hamburger menu triggers a re-render of child elements within the layout

I am currently working with React and Material UI v5. Within my layout, I have a menu component with children. Whenever I click on the menu, it triggers a refresh of the children components. I attempted to resolve this by encapsulating the child components ...

Deciding whether an item qualifies as a Map in JavaScript

I have been working on developing a function that will return true if the argument provided to it is an instance of a JavaScript Map. When we use typeof new Map(), the returned value is object and there isn't a built-in Map.isMap method available. H ...

Is there a way to retrieve a large number of users through an API using async await?

I am trying to retrieve all users from an API and I want to identify which user receives the highest payment. For instance let users=['tom','jenny','smith','Joe'] async function getUsers() { let response = awa ...

Why won't console.log function execute in this particular situation?

(function( $ ){ $.fn.openlayers = function( mapElementId, options ) { alert(console.log); console.log(options); ... } }); While attempting to enhance the capabilities of a JavaScript library, I encountered an unexpected issue. ...

FadeOut Television static on Canvas after a period of inactivity

Is there a way to smoothly fade out the TV noise after a specific timeout period? I found this code snippet on Stack Overflow that seems to address a similar issue: var canvas = document.getElementById('canvas'), ctx = canvas.getContext( ...

Place the object into a vacant area with the help of jQuery Sortable

I am using jQuery Sortable and it's functioning well. However, I have encountered a small issue that I need help with.    I have two blocks where elements from one block can be moved to the other. The problem arises when all the elem ...

Exploring the distinctions within a multidimensional array using PHP

I've got a PHP array structured like this... Array ( [section1] => Array ( [1] => Array ( [item1] => 'green' [item2] => 'red' ...

When the ng-model is updated within a promise's .then() function, the ng-change

I've encountered an issue with ng-change in a select not triggering when I update the ng-model parameter within my promise.then function. Here's my select code: <select ng-model="currentReport" ng-options="rpt.ReportDisp for rpt in availa ...

C# Expanding an array by appending an additional element at the end

As I've been working on my program, I've noticed that the growing arrays I'm using are causing some performance issues. Specifically, Lists are slowing things down, so I switched to arrays which greatly improved performance. To add elements ...

What does the `Class<Component>` represent in JavaScript?

Apologies for the lackluster title (I struggled to think of a better one). I'm currently analyzing some Vue code, and I stumbled upon this: export function initMixin (Vue: Class<Component>) { // ... } What exactly does Class<Component> ...

magnificPopup experiencing difficulties when attempting to invoke a class that is dynamically generated within the HTML document

Currently, I am encountering an issue with the magnificPopup. Whenever I try to trigger the popup using the class 'popup-with-zoom-anim', it doesn't seem to work as expected. Has anyone else faced a similar problem before? <body> < ...

Combining strings within a string after a specific word with nested Concatenation

In a given string variable "str," I am looking to concatenate another string between "InsertAfterMe" and "InsertBeforeMe". str="This is a string InsertAfterMe InsertBeforeMe" s1="sometext" s2="soMoreText" aList=[1,2,3,4,5] The concatenated string shoul ...

The 'split' property is not present on the 'string | number | {}' type

Just starting out with Typescript and I've encountered an error stating that the split method does not exist on type number. I've tried narrowing down the type by checking the value's type, but so far it hasn't been successful. Below is ...

What is the process for extracting the value of a checkbox generated through JavaScript?

I recently came across a helpful post on Stack Overflow that provided sample code demonstrating how to display multiple list of checkboxes dynamically on a dropdown list. The function in the code was exactly what I needed for my webpage. However, I encount ...