2

How to work with object, if I want...

var object = { 'title': value };

alert( object[ /* Whatever */ ] ); // Should return 'title' NOT value

Thanks.

3
  • @All OP confirmed in a comment on a now-deleted answer that he/she really wants the string "title" -- the name of the property. Commented Nov 26, 2010 at 11:33
  • read this: quirksmode.org/js/associative.html Commented Nov 26, 2010 at 11:34
  • This question is similar to: How do I loop through or enumerate a JavaScript object?. If you believe it’s different, please edit the question, make it clear how it’s different and/or how the answers on that question are not helpful for your problem. Commented Dec 21, 2024 at 8:50

1 Answer 1

6

Use a for...in loop to enumerate an object's keys, like this:

for(var key in object) {
  alert(key);  //to get the key's value, use object[key]
}

To be safe, in case someone messed with the object prototype, use .hasOwnProperty() like this:

for(var key in object) {
  if(object.hasOwnProperty(key)) {
    alert(key);
  }
}
Sign up to request clarification or add additional context in comments.

4 Comments

+1 Might be worth mentioning hasOwnProperty. :-) And possibly ECMAScript 5's Object.keys.
Nick, I must say... You are the Javascript God! Thank you!
@Marry - you're kind :) there are lots of brilliant people here, many much smarter than I...and some of the top JavaScript guys aren't here at all ;)
here is some Scriptures for you - developer.mozilla.org/En/JavaScript :-)

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.