0

If I have an array and an object is it possible to use the array values as field name to get the object field value?

Like this:

var x = ['foo', 'bar'],
    y = {
        foo: 'foo,foo',
        bar: 'bar,bar'
    }

for (var i = 0, l = x.length; i < l; i++) {
    console.log(y.x[i]);
    // Uncaught TypeError: Cannot read property '0' of undefined 
}

Except, this doesn't work.

Demo

Update

what if one of the object fields is a method like :

y = {
    foo: 'foo,foo',
    bar: function () {
        alert('');
    }
}

1 Answer 1

4

you need to use bracket notation as you are dealing with a variable key

console.log(y[x[i]]); 

Demo: Fiddle

y.x[i] tries to read a property x of y which does not exits so the [0] throws an error.

Sign up to request clarification or add additional context in comments.

7 Comments

what would you do with functions
yes if one of them is a function i notice it will yield the function as string
@MinaGabriel do you want to invoke the function
just add () to the function reference like y[x[i]]()
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.