Enhance the structure of this array data model

Currently in the process of creating a small script to tag coordinates in an array:

var countries = ['spain','australia'];
var leftX   = ['270','575'];
var topY    = ['60','220'];

When I need to retrieve them:

country = 'spain';
var left_ = leftX[countries.indexOf(country)];
var top_ = topY[countries.indexOf(country)];

This setup might be a bit confusing for my colleagues when updating. Any suggestions on how to simplify it?

Answer №1

var locations = {
    "greece":  {
         leftX: '310',
         topY: '85'
    },
    "japan":  {
         leftX: '495',
         topY: '150'
    }
}

//Next:
country = 'greece';
var left_ = locations[country].leftX;
var top_ = locations[country].topY;

Answer №2

I prefer organizing it in an object structure:

let countries = {
    usa: { leftX: 200, topY: 80 },
    // etc
}

This way, accessing the data becomes much simpler and there's no need to be concerned about support for .indexOf() (which may not work in older versions of IE):

country = 'usa';
var leftValue = countries[country].leftX;
var topValue = countries[country].topY;

Answer №3

In my approach, I prefer utilizing JavaScript objects for this particular task.

let countries = { mexico: {leftX: 150, topY: 100}, japan: { leftX: 400, topY: 300};

countries.mexico.leftX; // 150
// or
countries["mexico"].leftX; // 150
// or
countries['mexico']['leftX']; // 150

There are various ways to access the data in a traditional JavaScript way.

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 return value cannot be retrieved from a promise function in Node

I'm facing an issue where the return value of a certain function is being executed before the actual result is returned. Can anyone provide guidance on how to solve this? Thanks! exports.addUser = async (data) => { const updateduser = await db.U ...

Guide to setting up a nested vuetify navigation drawer

I am facing a scenario where I have one fixed navigation drawer with icons and another dynamic navigation drawer that should open and close adjacent to the fixed one without overlapping. The current implementation is causing the dynamic drawer to overlap t ...

Angular.js: The Best Way to Attach a "Change" Event to a Service

Just starting out with angular.js... I have a HTML5 page where I can input new URLs along with names. Now, I need to validate these URLs against a back-end service to see if they already exist. How can I trigger the “onChange” event on the input field ...

Unable to access component data while inside a v-for loop scope

I recently started using Vue and I'm having trouble accessing my component data within a v-for loop. After implementing the code below, I encountered this error message. TypeError: Cannot read property 'whatever' of undefined at eva ...

The data structure '{ variableName: string; }' cannot be directly assigned to a variable of type 'string'

When I see this error, it seems to make perfect sense based on what I am reading. However, the reason why I am getting it is still unclear to me. In the following example, myOtherVariable is a string and variableName should be too... Or at least that&apos ...

Tips for displaying the date in 13-digit Unix Timestamp format using JSpreadSheet

I am faced with a challenge involving data that is stored in Unix Timestamp format, which I need to display as a readable date (e.g. YYYY/MM/DD) in JSpreadSheet ("jspreadsheet-ce"). Currently, the data appears as a 13-digit number and looks unattractive. ...

Jasmine - What is the best way to simulate a finally block?

After creating a controller in my test, I encountered an issue with the updateActionList function... this.createScope = function(scope) { if (scope) { this.scope = scope; } else { this.scope = $rootScope.$new(); } this.contro ...

Generate a selection of complementary, triadic, and monochromatic color palettes using just one hex color code

My goal is to generate three unique color palettes based on a single hex/rgb value given by the user. The first palette will feature the complementary color of the initial input, followed by a full range of colors in subsequent palettes. I aim to expand be ...

Combining and adding arrays that share the same key

Currently, I am working with a for loop that extracts data for each user from the matchlistResponsestats object. Once the for loop completes its iterations, I end up with approximately 90 arrays in this format: ["username", kills, assists, deaths] My goal ...

The issue of empty req.body in POST middleware with Medusa.JS

Feeling completely frustrated with this issue. Grateful in advance to anyone who can lend a hand. Any insights on why req.body is showing up empty? Medusa.JS should be utilizing bodyParser by default, correct? It was functioning fine earlier today but now ...

Is it possible to incorporate a PHP line within a Handlebars context array?

I'm currently utilizing handlebars along with a handlebars register helper to iterate through an array that I've included in my context. The result is then displayed as an unordered list (ul). However, I'm facing an issue when attempting to ...

What is the best way to access the element menu with element-ui?

I am looking for a way to programmatically open an element in my menu, but I haven't been able to find any information on how to do it. HTML <script src="//unpkg.com/vue/dist/vue.js"></script> <script src="//unpkg.com/<a hr ...

Trouble getting the onclick event to function properly with PHP, ajax, and jQuery

I am looking to incorporate an onclick event using PHP to achieve a specific goal. My aim is to utilize ajax to prevent page refreshing and generate buttons upon click events. I am uncertain about merging the div buttons with the ajax outcome. The PHP fi ...

A guide on validating dates in Angular Ionic5 with the help of TypeScript

I have tried multiple solutions, but none seem to work when validating the current date with the date entered by the user. The date is passed from the user into the function parameters, but how do I perform validation? How can I validate the date? isToday( ...

Particle JS - Taking over the entire screen

I have incorporated Particle JS into the banner using the link provided. It should be confined within the banner, with a white background underneath displaying the header text "hello there." However, the Particle.JS effect is currently taking over the enti ...

What is the best way to sort an array of objects while simultaneously evaluating against another object?

My search involves looking through a list of cars that have various attributes such as make, model, price, and more in order to compare them to the specific car I am searching for via a form. While I understand how to compare two cars directly, I am uncer ...

Recognition of the ng-click function in Ionic buttons can occasionally be unreliable

I am experiencing an issue with my Ionic app that wraps a web-app using Angular. Within the app, there are buttons coded like this: <ion-view view-title="Orders"> <ion-content scroll="true" overflow-scroll="true"> <div class="row"> ...

The requested resource does not have the 'Access-Control-Allow-Origin' header, resulting in a 401 error

I've been working on integrating spell check functionality using the Bing Spell Check API, but I've run into a 401 error. The specific error message is: The requested resource does not have an 'Access-Control-Allow-Origin' header. This ...

Cannot get the before-leave transition JavaScript hook to function properly in Vue.js

I am facing an issue with my variable, transitionName, in the beforeLeaveHook function. Despite attempting to change it to 'left', the value remains stuck at 'right'. Any assistance on resolving this matter would be greatly appreciated. ...

Bootstrap4 does not support the <button> element

How can I achieve a 'collapse icon' floated to the left followed by Copyright © using Bootstrap 4? I've looked at similar questions on this topic, but none seem to provide a direct answer. Other questions contain different code with ob ...