0

Example:

var o = {'key': 'value'};
var key = 'key';
console.log('key' in o); //true
console.log(key in o); //false

How to do this? =)

4
  • The second log is true as well. Providing a string literal directly or a variable containing a string value has the same effect. Commented Jul 6, 2013 at 19:27
  • 3
    Both should be true. With what did you test? Commented Jul 6, 2013 at 19:28
  • 2
    What a ridiculous question and answers... Commented Jul 6, 2013 at 20:06
  • Lol actually I made this post by mistake - @amadeus is right =) Commented Jul 6, 2013 at 20:09

2 Answers 2

5

I'd suggest:

o.hasOwnProperty(key);

JS Fiddle demo.

References:

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

3 Comments

I am an evil ninja... ;)
And what exactly does this answer?
I was under the impression that this answered the question: 'how [can I] check if Object has a certain key, when [that] key is [a] variable?' Does it not?
3

Try hasOwnProperty:

o.hasOwnProperty(key);

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.