Implement pagination for an array in JavaScript

I am seeking a solution involving displaying a JavaScript object in a paged format. For instance, given the sample object below, I aim to present it as pages based on the value stored in the perPage variable.

{
   "fruits":[
     {
       "from":"Shanghai",
       "to":"Houston",
       "createdOn":"2019-02-20 17:02:45",
       "threadId":"1234564534"
     },
     {
       "from":"Mumbai",
       "to":"Texas",
       "createdOn":"2019-02-22 17:02:45",
       "threadId":"223455678"
     }
   ],
   "vegetables":[{
     "from":"Barcelona",
     "to":"Milan",
     "createdOn":"2019-01-20 10:02:45",
     "threadId":"45673456"
   }],
   ...
 

If perPage is set to 5, the display should look like this:

<div class="page"> 
  fruits
  vegetables
  ...
</div>
<div class="page">
  ...
</div>

In case perPage is adjusted to 2, there will be three divs with the class page. The first div will show fruits and vegetables, the second will feature paper and books, while the third will display toys and electronics.

I have devised a basic Vue.js code for this purpose, but it encountered issues under certain circumstances. Could someone take a look at this and identify where it went wrong?

  <div class="wrapper">
<div v-for="(eachWidget, widgetName, index) in widgetData">
<div v-bind:class="((index != 0) && ((index%perPage) == 0))?'page':''" >
  <div class="widget">
    <p>{{ widgetName}}</p>
    <p class="card" v-for="(eachItem, index) in eachWidget">{{eachItem.from}}</p>
  </div>
</div>

Answer №1

Initially, I determined the number of pages by considering the length of items and the value of perpage. After that, for every page, I displayed the items list and verified the index of each item in relation to v-if:

new Vue({
    el: "#app",
    data: {
        perpage: 5,
        items: {
            "fruits": [{
                "from": "Shanghai",
                "to": "Houston",
                "createdOn": "2019-02-20 17:02:45",
                "threadId": "1234564534"
            }, {
                "from": "Mumbai",
                "to": "Texas",
                "createdOn": "2019-02-22 17:02:45",
                "threadId": "223455678"
            }],
            "vegetables": [{
                "from": "Barcelona",
                "to": "Milan",
                "createdOn": "2019-01-20 10:02:45",
                "threadId": "45673456"
            }],
            "paper": [{
                "from": "Kualalumpur",
                "to": "Singapore",
                "createdOn": "2019-02-01 12:02:45",
                "threadId": "234222345"
            }, {
                "from": "Singapore",
                "to": "Vancover",
                "createdOn": "2019-01-20 11:02:45",
                "threadId": "6756434343"
            }],
            "books": [{
                "from": "Jibooty",
                "to": "Ahmedabad",
                "createdOn": "2019-02-10 17:02:45",
                "threadId": "23456789"
            }],
            "toys": [{
                "from": "Shanghai",
                "to": "Houston",
                "createdOn": "2019-02-20 14:02:45",
                "threadId": "123434343"
            }],
            "electronics": [{
                "from": "Somalia",
                "to": "Angora",
                "createdOn": "2019-02-20 17:02:45",
                "threadId": "667676767"
            }]
        }
    },
    computed: {
        length() {
            return Object.keys(this.items).length
        },
        pages() {
            return Math.ceil(this.length / this.perpage)
        }
    }
})

// code snippet to hide vue warnings
Vue.config.productionTip = false;
Vue.config.devtools=false;
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <label>Items per page:</label>
  <input type="number" v-model="perpage" min="1" :max="length">
  
  <ul v-for="n in pages">
    <li v-for="(item, title, index) in items"
    v-if="index >= perpage * (n-1)  && index < perpage * n">
      {{ title }}
    </li>
  </ul>
  
</div>

I trust this information proves helpful.

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

How can we determine which MenuItems to open onClick in a material-ui Appbar with multiple Menus in a React application?

While following the examples provided on the material UI site, I successfully created an AppBar with a menu that works well with one dropdown. However, upon attempting to add a second dropdown menu, I encountered an issue where clicking either icon resulte ...

Puppeteer patiently waits for the keyboard.type function to complete typing a lengthy text

Currently, I am utilizing puppeteer for extracting information from a particular website. There is only one straightforward issue with the code snippet below: await page.keyboard.type(data) await page.click(buttonSelector) The initial line involves typin ...

Updating the Keycloak token in VueJS using keycloak-js even when it is still valid

I have implemented a VueJS frontend connected to Keycloak using keycloak-js openid, without using the implicit flow https://i.sstatic.net/BxhJh.png Currently, there is a scenario in which the Backend NodeJS adds groups to a user in Keycloak. However, in ...

The Vue CLI build is displaying a blank page when hosted on an Apache server

I encountered an issue with vue cli. Running npm run serve went smoothly, but when I tried dev mode using npm run build-dev, the build process finished with a blank page displayed. The error message received was "Uncaught SyntaxError: Unexpected token &ap ...

What steps can I take to eliminate the warning "Warning: Prop `style` did not match" that appears when I bring in the Image component in Next.js?

Hi there! I'm encountering a warning when trying to import an image using the Image component in nextjs. The warning message reads: Warning: Prop style did not match. Server: "display: block; max-width: 100%; width: initial; height: initial; ba ...

The newly added radio button does not function as a separate group as expected

I currently have a set of radio buttons: <input type="radio" class='form-control' name="progress_type[]" value="Journal Papers"><span class='radio-label'>Journal Paper</span> <input type="radio" class='form-co ...

What is the method of including a null option in a dropdown menu?

I have a basic dropdown menu with the placeholder text "none." I want users to be able to clear their selection without adding another option to the dropdown. Can anyone help me achieve this? Thank you! Below is my code snippet: Check out the live demo h ...

Looking through a Json file and retrieving data with the help of Javascript

I am currently working on developing a dictionary application for FirefoxOS using JavaScript. The structure of my JSON file is as follows: [ {"id":"3784","word":"Ajar","type":"adv.","descr":" Slightly turned or opened; as, the door was standing ajar.","tr ...

Obtain the breakpoint value from Bootstrap 5

We have recently updated our project from Bootstrap 4 to Bootstrap 5. I am trying to retrieve the value of a breakpoint in my TypeScript/JavaScript code, which used to work in Bootstrap 4 with: window .getComputedStyle(document.documentElement) .g ...

Utilizing jQuery's Chained Selectors: Implementing Selectors on Previously Filtered Elements

DO NOT MISS: http://jsfiddle.net/gulcoza/9cVFT/1/ LATEST FIDDLE: http://jsfiddle.net/gulcoza/9cVFT/4/ All the code can be found in the above fiddle, but I will also explain it here: HTML <ul> <li id="e1">1</li> <li id="e2" ...

Executing functions from within a VueJS component using included bootstrap or jQuery scripts in the template/layout

As a beginner in VueJS, I am looking to create an Admin Dashboard using the SB Admin Pro bootstrap template that we have already purchased. While BootstrapVUE is available, we are committed to utilizing the specific template we own. My Objective: Within o ...

Performing simultaneous document queries within a single API in MongoDB

I am currently working with an API written in typescript and attempting to execute parallel queries for the same document by using Promise.allSettled. However, I have noticed that it is performing poorly and seems to be running sequentially instead of in p ...

Modify the background's color and incorporate a pointlight using three.js

Recently, I have been exploring the capabilities of three.js. One interesting challenge I encountered was creating a cube within a wireframe cube. However, I found myself struggling to alter the background color in my project. I believe that incorporating ...

Is it possible to generate a basic HTML page using Express JS without utilizing Ejs or any other templating engine

I have a basic HTML file with a Bootstrap form, along with a simple API coded within. In my server.js file, I've specified that when I request /about, it should redirect me to the about.html page. However, instead of redirecting, I'm encountering ...

The error encountered is related to the MongooseServerSelectionError that occurs in

I have been working on setting up my first mongo-db application to connect to the server. However, I am encountering a specific error during this process: const express = require('express'); const mongoose = require('mongoose'); const ...

Tips for simulating focus on a Material-ui TextField with a button press

My web application features a unique method for indirectly filling in text fields. Since there are multiple clicks involved (specifically in a calendar context) and numerous fields to fill, I want to provide users with a visual indication of which field th ...

retrieve profile data asynchronously from the database

I am trying to retrieve data from a database using asyncData and Axios. Below is the code I have been using. However, no request is being sent and I suspect there might be an error in my code. Can someone please assist me in identifying and resolving the ...

Node.js and Couchbase integration: A closer look at the functionality of the add() method

As I dive into learning about couchbase, I encountered a basic issue with inserting data using the add() method in my couchbase instance. Despite troubleshooting, something seems amiss in my code and I'm unable to pinpoint the exact reason. var http ...

How can labels be added when mapping over JSON data?

If I have JSON data structured like this: { "siteCode": "S01", "modelCode": "M001", "modelDesc": "Desc01", "price": 100 "status": "A", "startDate": "Ma ...

The definition of require is missing in the MEAN stack node

Currently experimenting with building an application on the MEAN stack and encountered a hurdle involving the use of Node's require function. Here is my current project structure: -- app -- images -- scripts -- app.js // configuration fi ...