0

I have a simple object and I want to call a particular property by passing a property name through a function:

spit(name);

function spit(value) {
    var test = new Object();
    test.name = "Bill";
    test.number = 24;
    console.log(test.value);
}

The above code should return "Bill". How is this possible?

1
  • I'm sorry, I was confused with arrays. Commented Nov 17, 2011 at 23:48

3 Answers 3

5

Sounds like you're looking for something like this:

spit('name');

function spit(value) {
    var test = new Object();
    test.name = "Bill";
    test.number = 24;
    console.log(test[value]);
}
Sign up to request clarification or add additional context in comments.

1 Comment

This works, but only when I call the function with value as a string. spit('name'). Thanks! Was having a brain fart.
0

You are returning the value property, which has not been defined for the object. Also, you aren't quoting your parameter when calling spit(), which might be a problem.

Try using this:

function spit(value) {
    var test = new Object();
    test.name = "Bill";
    test.number = 24;
    console.log(test[value]);
}

spit('name');

Comments

0
function spit(value) {
    var test = {
       name: 'Bill',
       number: 24
    }

    test[value] = value;

    return test.value;   
}

Comments

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.