Leveraging a variable to retrieve a specific element from an array in JavaScript

I'm encountering an issue while attempting to use a variable for accessing an array value resulting in an undefined error.

var ordernum = 54;
keys[ordernum][ "keys" ];

Uncaught TypeError: Cannot read property 'keys' of undefined

When I try keys["54"][ "keys" ]; it works perfectly. However, due to being within a for loop, I need to utilize the variable.

Is there a way for me to achieve the same result using the variable?

Snippet from the complete code:

    var customers = <?php if ( isset($customers) ) { echo json_encode($customers); } ?>;
    var keys = <?php if ( isset($keystable) ) { echo json_encode($keystable); } ?>;

for ( var i = 0; i < customers.length; i++ ) {
            var ordernum = customers[ i ][ "order" ];
            table += '<tr bgcolor="#ffffff">';
            table += '<td>' + customers[ i ][ "email" ] + '</td>';
            table += '<td>' + customers[ i ][ "org" ] + '</td>';
            table += '<td style="width:450px;">' + customers[ i ][ "notes" ] + '</td>';
            table += '<td>' + keys[ordernum.toString()][ "keys" ] + '</td>';
            table += '</tr>';
        }

Answer №1

Here is a potential solution that may meet your needs:

let orderNumber = 54;
const key = keys[orderNumber + ""]["keys"];

Answer №2

If the condition keys["54"]["keys"] is satisfied, it indicates that the first key is a string. In such case, you must convert the variable to a string.

var ordernum = "54";
keys[ordernum][ "keys" ];

or

var ordernum = 54;
keys[ordernum.toString()][ "keys" ];

Answer №3

It seems like what you're proposing is quite challenging (not exactly impossible but it would require a bit of javascript wizardry involving proxies that may not be applicable in your situation).

Chances are that the keys you're searching for aren't simply "54", but could be " 54", "054", or something along those lines.

To determine the actual keys, you might want to try something like this:

console.log(JSON.stringify(Object.keys(keys)));

Another common mistake is when asynchronous data gathering (AJAX) is used and your loop executes too soon (you should place your processing within the callback function rather than running it immediately after making the AJAX call).

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

AngularJS Error: $element.find(...) does not support iteration

I'm attempting to utilize a datatable in my AngularJS application. Below is the HTML code I've implemented: <div ng-app="datatable"> <div ng-controller="voucherlistcontroller"> ...

Ways to update the content within an IFRAME using server-side methods

I've searched through many posts, but I still haven't found a clear solution to my problem. Here's what's going on: I have a page with an IFRAME that is pulling content from a different domain. The style of the frame doesn't match ...

Setting cookies in Express will not work if you are using res.sendFile()

After implementing the res.sendFile() function, I noticed that the set-cookie header is not being received in the response. app.get(sessionTracker, (req, res, next) => { res.cookie('tracker', '123a', { maxAge: 172800000, h ...

Is it not possible to cast the incorrect type of the Typescript array.from(iterator)?

Encountering an error when converting flow code to typescript involving iterators. There seems to be a missing element in the iterator. const iter: Iterator<RouteData> = contentMap.routes(); const contentArray: Array<RouteData> = Array.from(it ...

Executing JavaScript file using TypeScript code in Node.js

Is it possible to execute a JS file from TypeScript code in Node.js? One way to achieve this is by exposing the global scope and assigning values to it. For example: Global Scope (TypeScript): globalThis.names = ['Joe', 'Bob', 'J ...

Automated static file versioning in Google App Engine/Python

Recently, I've been experimenting with Google's page speed service, and it has inspired me to implement automatic versioning of static files in my GAE/P application. This way, I can fully utilize longer caching times. Developing a script to perf ...

Extracting multiple data from another array using SimpleXML

Need help with importing data from XML to database using the provided code: $a = glob('data/*/*.xml'); echo "importing categories ...... "; foreach ($a as $i) { $xml = simplexml_load_file("$i") or die ("Error: Cannot load file"); forea ...

Tips for effectively utilizing the useDraggable and useSortable hooks within the dnd-kit library

I'm currently working on developing a basic calculator using React and dnd-kit. The idea is to have draggable elements in the calculator that can be sorted within a droppable area with smooth animation effects. However, I've encountered an issue ...

The code automatically assigned a value to a variable without any external input

While working in C, I came across an unusual situation with an integer named 'toplam.' Despite not assigning any value to it, a value of 16 appeared when I checked the watches window. To confirm my observation, I utilized an online C compiler and ...

What are the possibilities of using lists or arrays in GraphQL variables

Exploring the possibility of using an array/list as a variable for a GraphQL mutation: Schema type User { id: Id! email: String name: String bookmarks: [Bookmark] } type Mutation { updateUser(data: UserInput!): User } input UserInput { emai ...

Is Vanilla JS or React the Superior Choice for Building NPM Packages?

As a newbie with a few ideas for npm packages, I could use some guidance. I've noticed that tutorials on YouTube often focus on writing packages in vanilla JavaScript, while some GitHub repositories show packages created with React. My objective is t ...

Opting out of code splitting in Webpack for Node target

In my node application, I am using react-router to render React views server-side. My challenge lies in the implementation of code splitting using require.ensure on the client-side while wanting to avoid it when compiling server-side code. Below is an exce ...

What is the best way to increase a percentage width by a certain percentage using javascript?

My goal is to gradually increase the filled amount of a progress bar using JavaScript. I have created a function called nxt() that should add 3.3% to the width of the progress bar every time it is called (for example, from 2.0% to 5.3%). However, my curren ...

Tips for iterating through data in JSON format and displaying it in a Codeigniter 4 view using foreach

As a newcomer to JSON, I have a question - how can I iterate through JSON data (which includes object data and object array data) using jQuery/javascript that is retrieved from an AJAX response? To illustrate, here is an example of the JSON data: { "p ...

Node.js project is set up globally on personal system

Introduction I'm diving into the world of Node.js and eager to learn. NPM has been a game changer for me as I can easily install packages globally and utilize them as standalone applications accessible from anywhere on my system. To my surprise, thi ...

Data structures of advanced complexity within HTML data attributes

I am delighted by the existence of the html5 data attribute. It's great to be able to input a plain string into html attributes and retrieve them using jquery. However, wouldn't it be wonderful to have more than just a basic string? Is there a ...

css effect of background image transitioning on mouse hover

Is there a way to have an element on my webpage with a background image that follows the movement of the mouse when hovered over? I want it to be similar to this website: This is the HTML code I currently have: <section id="home" data-speed="3" data-t ...

Remove all of the classes from the specified element using JavaScript

I have a button and I want to remove all the classes when it is clicked. Here is what I have tried: button.style.className = '' document.querySelector('button').onclick = function() { this.style.className = ''; } .myClas ...

Is it possible to retrieve JavaScript object properties using HTML elements?

I have fetched an array of objects using jQuery.getJSON(). Each object should be represented by an HTML div element, allowing users to click on the element and access all properties of the corresponding object. What is the most efficient approach for achie ...

Learning how to effectively utilize arrays in VB before initializing values

In my VB program, I am attempting to populate an array through a loop that reads a .txt file and saves each line into the array. However, I keep encountering the error message "Array is used before it has been assigned values". Dim fileEntries As String() ...