What is the best way to retrieve the array length in a JavaScript/angularJS i18n file?

Here is the structure of my translation file:

{
    "RANDOM": [
      {
        "ITEM": "basdf"
      },
      {
        "ITEM": "casdf"
      },
      {
        "ITEM": "dasdf"
      },
      {
        "ITEM": "easdf"
      }
    ]

}

The goal is to display one item randomly:

getQuestion() {
  const sizeOfRandomItems = 4;
  const randomNumber = Math.floor(Math.random() * sizeOfRandomItems);
  return this.$filter('i18n')('RANDOM.' + randomNumber + '.ITEM');
}

The issue arises when adding a new item, as sizeOfRandomItems needs manual updating. Is there a way to dynamically get the array size of RANDOM from the translation file?

I attempted the following:

const arraySize = this.$filter('i18n')('RANDOM'); 
console.log(arraySize.length);

However, I receive a warning:

i18n-translate.js:205 Missing key: 

It returns 6 (which represents the number of characters in the key holding the array RANDOM)

Answer №1

If you're open to using a library, one option is to load the JSON data with jQuery, parse it into an array, and then determine the array length. Keep in mind that this solution may become cumbersome if you have a large number of keys, so it's recommended to store the result in a variable for future use.

var length;
function getQuestion() {
  const sizeOfRandomItems = 4;
  const randomNumber = Math.floor(Math.random() * (length ? length : getJsonLength()));
  return this.$filter('i18n')('RANDOM.' + randomNumber + '.ITEM');
}

function getJsonLength() {
  $.getJSON("i18n.json", function(json) {
    var array = JSON.parse(json)
    length = array.length;
  });
}

Answer №2

To simplify the process, consider adding an extra item in your translation file that provides the current array length. This way, you can retrieve this information from the translation and use it accordingly.

getQuestion() {
  const sizeOfRandomItems = parseInt(this.$filter('i18n')('RANDOM.LENGTH'), 10);
  const randomNumber = Math.floor(Math.random() * sizeOfRandomItems);
  return this.$filter('i18n')('RANDOM.' + randomNumber + '.ITEM');
}

An even simpler approach would be to directly load the object from the translation file, similar to how it's done in i18next (https://www.i18next.com/objects-and-arrays.html). However, it's uncertain if this functionality is supported in the i18n library you are using.

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

Ways to trigger a JavaScript function upon submission of my form

I have created a code snippet to validate and submit a contact form: formValidation: function() { if ( this.formData.name && this.formData.company && this.formData.email && this.formData.industry && this.formData.phone && this.fo ...

Row index retrieval in Datatable is not possible following a search operation

I have successfully created a datatable and can retrieve the row index of the data before any search action is performed. dataArray=[ [1, "Name1"], [2, "Name2"], , [3, "Name23"], ]; var table = $('#tblName').DataTable( { ...

What is the most effective method for sharing features while maintaining unique aesthetics?

In the process of developing a Next.js website, I've encountered a challenge: I have 3 forms that function in similar ways but have different styles. Instead of duplicating code for each form, I'm looking for a way to build the form structure on ...

Create a feature that dynamically loads JSON Data onto a TableView in iOS as the user scrolls

I have developed an application that utilizes JSON data from web services. My web services consist of three pages, and when I add data to the tableview, it fills the first page. However, when I scroll the table view to the second page, the data from the fi ...

What steps can be taken to enable automatic playback for this slider?

After downloading the slider from this site, I've been attempting to enable autoplay on this slider but have not had any success. Can anyone provide guidance on how I can achieve this? I've tried modifying the code below without achieving the des ...

Lazy serialization in Protobuf streaming API

Our Android app utilizes Protocol Buffers for storing application data. The data is structured in a way where a single protobuf ("container") holds a list of other protobufs ("items") as a repeated field: message Container { repeated Item item = 1; } ...

Continuously inserting new records to a JSON file using a while loop

Is there a way to continuously add key value pairs to a JSON object within a while loop? var sName = "string_"; var aKeys = ["1", "2", "3"]; var sKey = "key"; var n = 1; var aObj = {}; var l = aKeys.length; for(let i=0; i < l; i++){ while(n < 5) ...

Having trouble sending an array from Flask to a JavaScript function

As a newcomer to web development and JavaScript, I'm struggling to pass an array from a Flask function into a JavaScript function. Here's what my JS function looks like: function up(deptcity) { console.log('hi'); $.aja ...

Leverage the fs module in Node.js using npm packages, without the ability to use it

In the process of developing a library using Webpack that must be compatible with both browser and Node.js environments, I encountered an issue. There is a single function within the library that requires the use of 'fs', specifically for compati ...

Empty req.body in Node.js when POST method is used

I'm completely new to exploring REST and Express, and I've been following this insightful tutorial on creating a REST API. Here's a glimpse of my programming journey through the lens of my app.js code: var express = require('express&ap ...

Obtain geographic information using a JSON fetch from a map

I am facing an issue while integrating Laravel API data into React. Although I can see the JSON data in the console after fetching it, I encounter an error when I try to display it in a table for listing. The error states that my .map function is not recog ...

Using React.js to compute dates based on user-inputted dates

Today was dedicated to tackling the coding challenge of creating a function. I'm currently working on a react app using the PERN stack. The form I'm working on includes multiple date inputs, with two date columns and a total days column. My goal ...

Align component within material-ui grid

Looking to center align the same cards but not just the grid component, I need the content itself to be equally distant from the borders and each other. I've searched and tried different solutions without luck. https://i.stack.imgur.com/aZj7H.png htt ...

Information is being displayed in the Console, but it is not appearing in the Component

I'm facing an issue with my Product.js component. It fetches data from the backend successfully, but when trying to render JSX using that fetched data, only the container div gets rendered without the actual data inside it. Here's the code snippe ...

Struggling to manage texbox with Reactjs

Currently working in Reactjs with Nextjs and encountering a problem with the "text box". When I use the "value" attribute in the textbox, I am unable to input anything, but when I use the "defaultValue" attribute, I receive a validation message saying "Ple ...

Node.js Middleware Design Pattern: Connectivity Approach

I am embarking on a journey to learn Javascript, Node.js, Connect, and Express as part of my exploration into modern web development stacks. With a background in low-level networking, diving into Node.js' net and http modules was a smooth process for ...

Making an AJAX call to a PHP script to add data

Could you assist me in understanding why my code is resulting in a double insert? I have a JavaScript function that makes an AJAX request to a save.php file to insert data into a database. However, each time I submit it, it performs the insertion twice, al ...

What is the best way to choose the current Div's ID, as well as its Width and Height properties?

Within this section, there are four div elements with varying widths, heights, and colors that appear and disappear when their respective buttons are clicked. I am adding an "activeDiv" class to the visible div in order to easily select it using that class ...

Creating a recursive function in JavaScript to build a menu list object

Having an assortment of ['/social/swipes/women', '/social/swipes/men', '/upgrade/premium']; The objective is to create a map object that mirrors this structure: { 'social': { swipes: { wom ...

The route on Heroku is functional when tested locally, but encounters issues when deployed in production

I have recently deployed a node project to a Heroku app successfully. However, I am encountering a "Cannot GET" error (404) on one specific route while other routes on the same page are functioning as expected. This issue only occurs when accessing the rou ...