-1

Possible Duplicate:
Dynamic object property name

With an ajax call I receive an object: E

This objects holds a number of child elements: width, height, etc.

console.log (E.width) gives me all elements of E.width

When I assign a var: tempElement = 'width'

Why does console.log(e.tempElement) returns 'undefined' and how can i access a child element of the object by a variable

$(function () {
    $('#widthSelect').on('change', function () {
        var updateArray = new Array();
        updateArray[0] = 'height';
        updateArray[1] = 'rim';
        updateArray[2] = 'load';
        updateArray[3] = 'speed';
        updateArray[4] = 'brand';
        updateArray[5] = 'season';
        getValues(updateArray);
    });

    function getValues(updateArray) {
        var data = updateArray.join('=&') + '=';
        $.ajax({
            type: 'POST',
            dataType: 'json',
            url: '******',
            data: data,
            success: function (e) {
                element = updateArray[0];
                console.log(e.element);
            }
        });
    }
});
Community
  • 1
  • 1

1 Answers1

2

Try this:

console.log( e[element] );

When you use "dot notation" like e.element then the bit after the . is taken literally as a property name. Your object doesn't have a property called "element" so you get undefined. If you use the array-style notation the bit inside the square brackets is evaluated as an expression and the result is used as the property name.

e.width
// is equivalent to
e["width"] // note the quotation marks
// and equivalent to
someVariable = "width";
e[someVariable]
// and also equivalent to
e[someFunction()]  // assuming someFunction() returns the string "width"
nnnnnn
  • 147,572
  • 30
  • 200
  • 241