0

I am trying to use the value from a select dropdown list as a variable for a Json filtering function. When I hardcode the value of a.(name), it works, but when I try to use the keyname var from the dropdown list it returns undefined.

function sortJson(a, b)
{
    //get sorting dropdown value for key
    var keyname = $('#sortByKey').val();// I want to dynamically set the keyname from dropdown. It traces correctly, so I am getting the value I want.

    if (a.keyname == b.keyname)//works when i hardcode a.name, or a.id etc...
    {
        return 0;
    }
    return a.keyname > b.keyname ? 1 : -1;
};

2 Answers 2

1

you juste have to write:

a[keyname]

instead of

a.keyname

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

Comments

1

To reference the properties of the variable with the name specified by keyName, use the brackets syntax as another answer suggested:

a[keyname]

This is equivalent to a.key if keyname is key, but will allow you to use a dynamic string.

a.keyname tries to lookup the keyname property on a, which does not exist.

2 Comments

Thanks, I appreciate it. I don't know what I was thinking.
No problem. A bit of stack overflow advice, generally if you want to thank someone here, upvote their answer/question. Thanks in the comments/question are generally frowned upon since they add noise: meta.stackexchange.com/questions/17878/…

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.