Dave Everitt
Dave Everitt

Reputation: 17871

Javascript 'undefined' when using a function variable on an array of objects

I have the following (example) array of objects:

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

and this function, which works fine to loop through them:

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

However, if I want to abstract this function for use on similar arrays by using function variables to access objects within them, 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>';
    }
}

'undefined' is the result when called as below (as I'd kind of expect since 'arrId' is not an object name):

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

How can I use the values passed to the function's variables to access values of objects within the array by name?


rewritten following advice against antipatterns:

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;
}

Upvotes: 1

Views: 1623

Answers (2)

Šime Vidas
Šime Vidas

Reputation: 186103

Try this:

function printValuesVar( arr, elemId, arrId, arrNum ) {
    var content = '';

    arr.forEach( function ( arrElem ) {
        content += arrElem[ arrId ] + ' = ' + arrElem[ arrNum ] + '<br>';
    });

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

Or a bit more advanced:

function printValuesVar( arr, elemId, arrId, arrNum ) {
    document.getElementById( elemId ).innerHTML = arr.map( function ( arrElem ) {
        return arrElem[ arrId ] + ' = ' + arrElem[ arrNum ];
    }).join( '<br>' );
}

ES5-shim for shitty browsers

Upvotes: 3

SergeS
SergeS

Reputation: 11799

Because you are loking for key "arrId", not the key stored in variable arrId

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

Upvotes: 2

Related Questions