Randomly loading Json files in Ionic is a great way to keep your

I have a div using *ngFor which loads values from a JSON file. I want to load values from different JSON files randomly each time the div is loaded. Is there a way to achieve this using Math.random() or any other methods?

html file 
      <div class="row" *ngFor="let data of mydata">
       <div class="col">{{data.number}}</div>
       <div class="col">{{data.code}}</div>          
      </div>



ts file

import { Component } from '@angular/core';
import { NavController, NavParams } from 'ionic-angular';

@Component({
selector: 'page-showall',
templateUrl: 'showall.html'
})
export class ShowallPage {

 constructor(public navCtrl: NavController, public navParams: NavParams) {

 }

// providing sample data for development instead of JSON.
  datas = [
{
  number: "1",
  code: "apple",

},
{
  number: "2",
  code: "orange",

},
{
  number: "3",
  code: "banana",

},{
  number: "50",
  code: "lemon",

}

  ];

  mydata = this.datas;

   // Using the 'mydata' variable in *ngFor to display values

 }

Answer №1

Your custom class specifies the JSON file it reads from and assigns it to the datas variable.

Initialize an array of locations to read from in your constructor:

public locations: Array<string>;

this.locations = ['firstLocation.json', 'secondLocation.json'];
let randomJsonFile = this.locations[Math.floor((Math.random() * this.locations.length) + 1)];

EDIT:
(OP added a more detailed question)

// Declaring arrays outside the constructor within the class

mydata: Array<Object>;
datas0: Array<Object>;
datas1: Array<Object>;
datas2: Array<Object>;
datasCollection: Array<Object>;

// Initializing arrays inside the constructor

this.datas0 = [
{ number: "1", code: "apple0" },
{ number: "2", code: "orange0" },
{ number: "3", code: "banana0" },
{ number: "50", code: "lemon0" }
];

this.datas1 = [
{ number: "1", code: "apple1" },
{ number: "2", code: "orange1" },
{ number: "3", code: "banana1" },
{ number: "50", code: "lemon1" }
];

this.datas2 = [
{ number: "1", code: "apple2" },
{ number: "2", code: "orange2" },
{ number: "3", code: "banana2" },
{ number: "50", code: "lemon2" }
];

this.datasCollection.push(this.datas0, this.datas1, this.datas2);

this.mydata = this.datasCollection[Math.floor((Math.random() * this.datasCollection.length) + 1)];

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

The YouTube Iframe API encountered an issue while attempting to send a message to an HTTP recipient. The recipient's origin

Encountering an error when using the YouTube Iframe API on Safari 9.1, OS X Yosemite Issue: Unable to post message to http://www.youtube.com. Recipient has origin https://www.youtube.com This problem only occurs in Safari, as other browsers like Firefo ...

Can we enhance this JavaScript setup while still embracing the KISS principle (Keep it simple, Stupid)?

I have completed the following tasks: Ensured all event handlers are placed inside jQuery DOM ready to ensure that all events will only run Defined a var selector at the top of events for caching purposes Please refer to the comments below for what I be ...

Providing static files in Express while utilizing mustache templates

I'm struggling to configure Express to serve a directory of static mustache files. I have an object with data like this: { a: 'Hello :)' b: 'Goodbye :(' } Along with two files: public/a.html <div>{{a}}</div> pu ...

Creating a List with Sublists that are displayed when hovering over the parent List is a key element of effective design

Hovering over 'View Rows' should open up both New Records and Old Records <div> <li>Add Rows</li> <li>DeleteRows</li> <li>View Rows <ul> <li>View New Records</li ...

Creating a JSON log file in Node.js

I am looking to save logs to a Json file newEntry = "User: " + lastUsername + " Time: " + now + " Door: " + IOSDoor; lastUserOpenClose += newEntry; jsonString = JSON.stringify(lastUserOpenClose); fs.appendFile("lastUserOpenClose.json", lastUserOpenClo ...

'Error: The type is missing the 'previous' property - Combining TypeScript with ReactJS'

I am quite new to using reactjs and ts. While I understand the error that is occurring, I am unsure of the best solution to fix it. Currently working with reactjs, I have created an: interface interface IPropertyTax { annul: { current: number; p ...

Switching the background color of a button on click and resetting the color of any previously clicked buttons (a total of 8

I'm struggling to implement a feature where only one button out of a column of 8 should be toggled yellow at a time, while the rest remain default green. Unfortunately, I can't seem to get the function to execute on click, as none of the colors a ...

The absence of a semicolon in the non-null assertion is causing an

Within my code, I have a function that arranges a set of cards according to a specific coordinate system: const orderCardsInPage = (items: OrderItemType[], pageCards: CardType[]) => { return pageCards.sort((firstCard, secondCard) => { con ...

Issues with Laravel 8's datatable scripts causing dysfunction

In my practice with the AdminBSB template, I am facing an issue where the Jquery datatable plugin JS is not functioning properly in my blade template. I aim to achieve a datatable layout similar to this example: https://i.sstatic.net/krfPl.jpg However, t ...

Having trouble accurately obtaining the height of a DIV element using jQuery

After trying to troubleshoot on my own, I ran into a roadblock due to my specific requirements not being met by existing solutions. The issue at hand is as follows: I have a sticky DIV element positioned to the left, nested within another DIV Element wit ...

I am encountering issues with my THREE.js RawShaderMaterial

I haven't encountered any issues when loading shaders created by others into THREE.js, but I've hit a roadblock when trying to create and run my own shader. The shader works perfectly on the platform where I designed it (), but it doesn't fu ...

Input specific ng-if conditions

I'm a bit confused about the conditions for my ng-if and could use some assistance. I have a form on my page that is rendered using ng-repeat and a couple of custom filters. You can check out this plunker. The issue I'm facing is that I need to p ...

The image tag fails to appear on the browser when the client attempts to access it

Greetings, I am new to web development. I am attempting to create a simple static website that only displays an image in the header tag of an HTML file. The server seems to be working correctly in sending responses to the client, but the problem lies in t ...

Tips for evaluating an array of objects in JavaScript

Welcome to the world of coding! Here's a scenario with an array: [ { "question1": "Apple", "question2": 5, "question3": "Item 1" }, { "question1": ...

How can I access the data variables from a JSON request within a function?

My task involves loading multiple JSON files from an array called bunchOfData, with each file having a corresponding URL. How can I access my variable "myI" within the processData function? for(var i = 0; i < bunchOfData.length; i++){ $.getJS ...

The scale line on the OpenLayers map displays the same metrics twice, even when the zoom level is different

When using the Openlayers Map scale line in Metric units, a specific zoom rate may be repeated twice during the zoom event, even though the actual zoom-in resolution varies on the map. In the provided link, you can observe that the zoom rates of 5km and ...

Parsing improperly formatted JSON from an HTTP GET request can be done using either AngularJS or JQuery

Trying to decipher a poorly formatted JSON response from a remote server that looks something like this: //[ {},{} ] In my AngularJS code: $http.get('http://www.example.com/badjson') .success(function(data) { console.log(data); }) ...

The size of objects on canvas is not consistent when loading with fabric.js loadFromJSON

Click here to view the code var canvas = new fabric.Canvas('canvas_1'); var canvas2 = new fabric.Canvas('canvas_2'); var imgObj = new Image(); imgObj.src = "https://gtaprinting.ca/wp-content/uploads/2021/05/blank-t-shirt-front-gre ...

Ionic Error: Module 'dezalgo' not found

When attempting to integrate the ios platform into my project for XCode development, I executed the command: ionic cordova platform add ios However, the following error occurred: ionic cordova platform add ios > cordova platform add ios --save module. ...

Seamless Exploration with Google StreetView

Google uses a special effect on StreetView images to transition smoothly between them. You can see an example of this effect in the images below, with the second image showing it being applied. My question is: How can I incorporate this same effect into m ...