JavaScript returns the value 'undefined' when a function variable is used with an array of objects

Here is an example of an array of objects:

var theArray = [
    {theId:'1', num: 34},
    {theId:'2', num: 23},
    {theId:'5', num: 26}
];

This function successfully loops through the array:

function printValues() {
    var i = 0;
    for(i; i<theArray.length; i++) {
        var obj = theArray[i];
        document.getElementById('result1').innerHTML += obj.theId + ' = ' + obj.num + '<br>';
    }
}

If you want to make this function more versatile for use with similar arrays, you can do so using function variables like this:

function printValuesVar(arr,elemId,arrId,arrNum) {
    var i = 0;
    for(i; i<arr.length; i++) {
        var obj = arr[i];
        document.getElementById(elemId).innerHTML += obj[arrId] + ' = ' + obj[arrNum] + '<br>';
    }
}

When calling the function like this:

printValuesVar(theArray,'result2','theId','num');

'undefined' is returned because 'arrId' and 'arrNum' are not recognized as object properties. To access them correctly, modify the function like this:


Updated function without anti-patterns:

function printValuesVar(arr,elemId,arrId,arrNum) {
    var i = 0;
    var content = '';
    for(i; i<arr.length; i+=1) {
        var obj = arr[i];
        content += obj[arrId] + ' = ' + obj[arrNum] + '<br>';
    }
    document.getElementById(elemId).innerHTML = content;
}

Answer №1

Check out these options:

function displayValues( array, elementId, idIndex, numIndex ) {
    var content = '';

    array.forEach( function ( element ) {
        content += element[ idIndex ] + ' = ' + element[ numIndex ] + '<br>';
    });

    document.getElementById( elementId ).innerHTML = content;
}

For a more advanced approach:

function displayValues( array, elementId, idIndex, numIndex ) {
    document.getElementById( elementId ).innerHTML = array.map( function ( element ) {
        return element[ idIndex ] + ' = ' + element[ numIndex ];
    }).join( '<br>' );
}

ES5-shim for outdated browsers

Answer №2

Your search should be focused on the key "arrId", rather than the key stored within the variable arrId

document.getElementById(elemId).innerHTML += obj[arrId] + ' = ' + obj[arrNum] + '<br>';

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

Trying to use 'cpa' before it is initialized will result in an error

I encountered the error stated above while using this particular route: router.put('/edit/:id', async (req, res) => { const cpa = await CPASchema.findById(req.params.id).then(() => { res.render('edit', { cpa:cpa }); cons ...

Utilize Flexbox to arrange elements in a grid layout based on specified number of columns and rows

My div is currently empty. <div id="container"></div> I have applied the following styling with CSS: #container{ display: flex; position: relative; flex-flow: row wrap; width: 100%; } The goal is to add more divs to the cont ...

Acquiring an icon of a program using its handle

I am looking for a way to extract a program's icon from its handle, which I acquired using User32.dll with EnumWindow/FindWindow. While I am aware of ExtractAssociatedIcon, it seems to work from a file instead of a handle. My question is how can I con ...

utilizing the data provided by a user in the "prompt" window within my HTML code

Looking to utilize user input from the prompt window. This is my custom JavaScript form: var answer; function load() { answer=prompt("what is your name?", "Write your name here"); return answer; } function hideNsee() { var HNS = docume ...

Once the getComponent is fully executed, move on to the getIndexRoute function

Within my react-router routes, I implemented plainRoutes in the following manner: getComponent (nextState, cb) { require.ensure([], (require) => { const CoreLayout = require('../layouts/CoreLayout/CoreLayout').default const u ...

Leveraging jQuery to Avoid Memory Leaks

After utilizing jQuery for a couple of months and delving into Javascript memory leaks for several days, I have two concerns related to memory leaks and jQuery: When I bind events (using .bind()) in jQuery, do I need to unbind them (.unbind()) before l ...

Redux, Retrieving the entire state rather than just the specified state

Experiencing a strange issue with react-redux. I am receiving all the state data instead of just the specific state that was passed. Here is the code snippet: Action.js import socketIOClient from 'socket.io-client' const DATA_URL = "LINK TO AP ...

Is there a way to identify a change in the URL using JQuery?

My goal is to clear the localStorage when a user navigates to a different page. For instance, if I am currently on . When the user goes to the URL, , I want to clear the localStorage. This is my script using JQuery. $(window).unload(function(){ if ...

The issue with Angular 2's Parameterised router link component not fully refreshing

I'm trying to figure out how to show a set of images when I click on a specific menu item. The menu structure looks like this: <ul id="demo23" class="collapse"> <li> <a [routerLink]="['image-gallery','Picasso ...

I'm attempting to solve the retrieved data from a firebase query, but unfortunately, the data is refusing to resolve

I've been attempting to retrieve data from firebase using Node.js, but I'm having trouble resolving it. Specifically, I need to extract the timestamp from the data stored in firebase. I've tried using promises and forEach loops, but haven&a ...

The dilemma between Nuxt Js global CSS and Local CSS

Currently, I am in the process of developing a Nuxt application utilizing an admin template. While I am well-versed in Vue.js, I am finding the aspect of loading assets within Nuxt.js to be a bit perplexing. I am in the process of converting the admin temp ...

What is the best way to display a PDF in a web browser using a JavaScript byte array?

I have a controller that sends the response Entity as a byte array in PDF form to an ajax call. However, I am struggling to display it in the browser despite trying various suggestions from old Stack Overflow questions. Here is the response from the Sprin ...

What is the best way to properly format letters with accents (such as French letters)?

I have encountered a challenge where I created a PHP file to display French text and then utilized this text in an AJAX file (specifically the responseText). The issue arises when trying to show the French responseText in an alert using JavaScript, as ac ...

Having trouble retrieving user login information in Postman

I have encountered an issue while creating a REST API using Node js and expressJs. When attempting to create a user, I successfully implemented the following code: /** * save user data from the user model */ router.post("/users", async (req, res) => ...

Retrieve a JSON file from the local file system using AngularJS

I recently started learning AngularJS and I am trying to read a JSON file from my local system. However, when I attempt to do so, I encounter an exception error that says: "Access to restricted URI denied XMLHttpRequest." Here is the code snippet: var de ...

ng-click not functioning correctly within templateUrl directive

Apologies if this appears to be a silly question, but I am new to Angular. I am facing an issue with an ng-click event that was functioning correctly until I moved the code into a directive. I suspect it has something to do with the scope, but I'm una ...

Switch up the appearance of a document by manipulating the stylesheet using a select tag

I'm currently facing an issue with the implementation of a drop-down box on my website for selecting different themes. Despite having the necessary javascript code, I am unable to get it working correctly. Here's the snippet: //selecting the sele ...

How to update or replace a complex nested object in MongoDB using Spring Data MongoDB

Hello, I am working with a specific type of document. { "id": "5a212b985735dd44089e4782", "people": [ { "personId": "5a212b985735dd44089e4783", "name": "Ronaldo", ...

What is the best way to trigger useEffect when the state being used within the effect is expected to change during the course of the effect's

Exploring the following code snippet: const [list, setList] = useState([]); const [curPage, setCurPage] = useState(0); const fetchItem = useCallback(async ()=>{ const data = await callAPI(); // data is an object setList(prev => [...prev, data]) ...

Refreshing CSS-Element-Queries following an ajax request

I’ve been utilizing css-element-queries from the https://github.com/marcj/css-element-queries repository to tailor styles based on an element's dimensions. However, I encountered an issue when dynamically adding elements via ajax calls. The new elem ...