1

Can I add Jquery Object to the blank object as key. For example:-

var obj = {};//blank object

var myId = $("#myId");//jQuery Object
var myId2 = $("#myId2");//another jQuery Object

obj[myId] = "Trying to add myId as a key";
obj[myId2] = "Trying to add myId2 as a key";

But the output of the obj contains only one key. Is the above thing is possible in JS or not?

Thanks in advance.

7
  • 1
    Javascript converts array keys to strings. Commented Jul 26, 2013 at 14:57
  • 1
    Why do you need this? Can you give us more information about what are you trying to do? Commented Jul 26, 2013 at 14:57
  • @DCoder So in the above code it is converting the keys to string. But why it is not adding both of the object as keyn in object. Commented Jul 26, 2013 at 14:59
  • Because $('#myId').toString() produces "[object Object]", and $('#myId2').toString() also produces "[object Object]". How do you expect to differentiate between them? Just like running obj = {}; obj.foo = 1; obj.foo = 2; and asking why you only get one key. Commented Jul 26, 2013 at 15:00
  • 1
    alert($('div').toString() === $('input').toString()) => true Why not use obj = {'#myId': $('#myId'), '#myId2': $('#myId2')}; Commented Jul 26, 2013 at 15:00

2 Answers 2

2

You have to use a string as property name (e.g. the id of the jquery object?).
See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects

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

Comments

1

If you want to keep the reference to object you can use an array of objects instead of an object:

[
   {
      "jQueryElement": myId1,
      "note": "Trying to add myId as a key"
   },
   {
      "jQueryElement": myId2,
      "note": "Trying to add myId2 as a key"
   }
]

Then you will be able to do:

function getNoteOfJqueryObj(element) {
 element = $(element);
 for (var i in array) {
     if (array[i].jQueryElement[0] == element[0]) {
         return array[i].note;
     }
 }
 return undefined;
}

I guess that this is one of the best ways you can choose.

JSFIDDLE

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.