Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use jQuery element object as array key?

Is it possible to use a jQuery element object as an array/object key?

Example:

var el = jQuery(this);
var test = {};
test[el] = "something strange";

Doing a:

jQuery.each(test, function(k,v){
    console.log(k);
});

just reports [object Object]

Is there a say that I could actually re-use the k as the original jQuery element object?

like image 748
Senica Gonzalez Avatar asked Mar 11 '12 23:03

Senica Gonzalez


People also ask

How to convert object into array in jQuery?

Answer: Use the jQuery $. map() Method You can simply use the $. map() method to convert a JavaScript object to an array of items.

How to iterate through an array of objects in jQuery?

The $. each() function can be used to iterate over any collection, whether it is an object or an array. In the case of an array, the callback is passed an array index and a corresponding array value each time.

How to traverse an array in jQuery?

Answer: Use the jQuery. each() function each() or $. each() can be used to seamlessly iterate over any collection, whether it is an object or an array. However, since the $. each() function internally retrieves and uses the length property of the passed array or object.


1 Answers

No, that is not possible.

ECMAscript only allows for strings as key-values for objects.


What you could do instead, is to use the id value from a single node instead. So it might look like

var el = jQuery(this);
var test = {};
test[this.id] = "something strange";

That of course requires the node to have an id value.

like image 52
jAndy Avatar answered Oct 21 '22 05:10

jAndy