Top strategies for managing fixed datasets

Imagine having a dataset containing country names and their corresponding phone prefixes, like so:

var countryPhonePrefixes = [
    {
        'name': 'Germany',
        'prefix': '+49'
    },
    {
        'name': 'France',
        'prefix': '+33'
    },
    // and many more entries
];

Including this in your development code could easily result in over 1000 lines (before minifying). My question is, are there any recommended approaches for handling and accessing datasets like this?

I have considered:

  • Keeping it within the code and utilizing IDE collapse functions to manage its visibility.
  • Moving it to a separate JavaScript file, where additional functionality related to the dataset can be implemented. Various JavaScript libraries support this approach.
  • Using AJAX to fetch the data. For example: jQuery.getJSON() from a .json file on your server; xhttp.open() & xhttp.send() to an API on your server, and so on.

Additional context: This dataset is needed for populating <option> elements in a country phone prefix selector used across multiple forms in the application. There is already an icon select feature in the application that aligns with the first solution I mentioned.

Answer №1

Storing 1000 lines of Javascript data in its own file is essential for efficient development. The size of the data makes it impractical to coexist with script logic.

If the data is static, consider saving and maintaining it in a separate file, then importing it into other files using a module bundler like Webpack. This will package the script into a single .js file for delivery to the client.

For dynamic data that changes between requests, avoid bundling it with other code. Instead, you have two options:

  • Send the data to the client through a network request. While effective, this method slightly delays making the data usable.

  • An alternative option is to embed the data within its own <script> tag. Your Javascript can then parse the contents of the script tag, like so:

const data = JSON.parse(
  document.querySelector('script[type="application/json"]').textContent
);

console.log(data);
<script type="application/json">[{"foo":"bar"}]</script>

Answer №2

If you want to retrieve prefixes using the name attribute, you can create an object where the name serves as the key and the corresponding prefix is the value.

This method streamlines the code and enables seamless access to the prefix information.

phoneCountryCodes = {
    Portugal: '+351',
    Germany: '+49'
};

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

Inserting HTML content into a DIV with the help of jQuery

Looking for a solution with my index.html file. I want to load other HTML files into a DIV by clicking on buttons. Here's an example of what I'm trying to achieve: I've searched through various examples online, but none seem to work for ...

Switch button while moving cursor

I'm struggling with getting this 2048x512 image, which has 4 stages of transition, to work properly. https://i.sstatic.net/1PBvX.png While I know how to switch it to the final stage on hover, I can't seem to figure out how to incorporate a trans ...

The domain retrieval is contingent on the language preference of the user

A task has been assigned to create a script in JavaScript/jQuery (or other suitable technologies) that will return a domain with a .pl extension if the user's browser language is set to Polish. Otherwise, the script should return a .eu domain extensio ...

Error message: "PHP encountered an issue with an undefined array key while attempting to

Hello everyone! I'm new to this community and eager to learn. Currently, I am diving into PHP and working on a program to upload files. I stumbled upon a tutorial with some code that seems a bit confusing due to my limited understanding of PHP termino ...

subscribing to multiple observables, such as an observable being nested within another observable related to HTTP requests

Hello, I recently started learning Angular and I am facing a challenge with posting and getting data at the same time. I am currently using the map function and subscribing to the observable while also having an outer observable subscribed in my component. ...

Converting JSON to CSV Using Python

i am currently working with a JSON file structured like this: { "temperature": [ { "ts": 1672753924545, "value": "100" } ], "temperature c1": [ { "ts": 167275392 ...

refetchQueries may be effective for specific queries

Using a Friend component within my AllFriends screen triggers the following mutation: const [deleteUserRelation] = useDeleteUserRelationMutation({ onCompleted: () => { Alert.alert('Unfriended'); }, refetchQueries: [{ query: ...

Tips for setting NgForm value within an Observable and verifying its successful implementation

Exploring the functionality of NgForm, I am testing to validate if the value of a form gets updated when the state of the store changes. @ViewChild('form') form: NgForm; ngOnInit() { this.subscription = this.store.select('shoppingList&apos ...

"AngularJS Bi-Directional Data Binding Issue: Unexpected 'Undefined

Recently, I've been tackling a project that involves using a directive. Initially, everything was smooth sailing as I had my directive set up to bind to ngModel. However, I hit a roadblock when I needed to bind multiple values. Upon making the necessa ...

Start multi-layered array

In my code, I have a matrix that contains a 4x4 array of double: typedef struct { double data[4][4]; } mat; This is how I declare my mat mat m1; I want to initialize my mat with zeros: double data[4][4] = { { 0,0,0,0 },{ 0,0,0,0 },{ 0,0,0,0 },{ 0, ...

The markers within a loop in react-native-maps are failing to render

Recently, I've been delving into the world of React Native app development for iOS. Specifically, I've been experimenting with the react-native-maps package. Here's the issue I'm facing: When I statically render a single MapView.Marker, ...

How can I create an input field that only reveals something when a specific code is entered?

I am currently developing a website using HTML, and I would like to create an admin section that requires a password input in order to access. After consulting resources on w3schools, I attempted the following code: <button onclick="checkPassword()" i ...

Scale the cylinder in Three.js from a specific point

Can a cylinder be resized along the Y-axis starting from a particular point? Instead of the cylinder expanding from its center in both directions to the new scale, is it possible for it to grow upwards/downwards only like a bar chart? Current code : fu ...

Unit testing an API built with Express and Mongoose using Jest

I have decided to implement a TDD approach for a user API that I am working on. Specifically, I am looking to add unit tests for two functions: userRegister and userLogin. Here is the code snippet from my app.js: 'use strict' const express = r ...

What is the best way to prevent event bubbling in this particular code snippet?

$('#div1').on('click', '#otherDiv1', function(event){ //Show popup $('#popupDiv').bPopup({ modalClose: false, follow: [false, false], closeClass: 'close ...

String Converted to Array of Key-Value Pairs

Looking to convert a key-value pair string into a functional array? Here's what I have so far: $Array = "'Type'=>'Honda', 'Color'=>'Red'"; $MyArray = array($Array); However, this code is not returning a ...

Pyinstaller error: File cannot be found at 'C:\Users\my.name\Desktop\EPE 2.0\dist\main\timezonefinder\timezone_names.json'. It seems to be missing

Whenever I attempt to run my executable file generated by pyinstaller (using the latest version, Python v3.6 in an Anaconda environment), I encounter the following error: File "site-packages\timezonefinder\timezonefinder.py", line 27, in <mod ...

The File Filter feature of Angular's ng2-file-upload is not functioning correctly for PNG files in the Internet Explorer

I am encountering an issue with the file uploader plugin ng2-file-upload when trying to upload a PNG file using Internet Explorer 11. For some reason, the PNG files are not being added to the queue, even though all other allowed file types work perfectly f ...

How to achieve a typewriter effect in React using JavaScript

I've been attempting to incorporate a typewriter effect into my website - at the moment, the animation is functioning but each letter appears twice (e.g. instead of reading "Welcome!" it displays "Wweellccoommee!!"). I suspect this is an asynchronous ...

I am attempting to activate the "about us" button on the website. I have successfully included the path and added a router link to the containing div of the button. However, there seems to be something

In my app, the first step involves specifying the path in the routing module. Following that is defining the home component, then the app component, and finally creating the button using HTML. Setting up the path in the app.routing.module.ts file <div ...