views:

54

answers:

2

I am returning some data (example below) and saving it to a jQuery object (or is this an array and I am confusing the two?) when I log the variable that is the object it has the values I am looking for but how do I access the data inside this object?

code

$itemPosition = {
    'top': $item.offset().top,
    'left':$item.offset().left
},

console.log($itemPosition);

This would log out (the in this case expected) top: 0 & left: 490.

But how can I know work with those values?

Also, while this it is probably obvious I am still in the early stages of learning jQuery/Javascript rest assured that reference books are on their way, but so far the SO community has been invaluable to my learning, so thanks for reading!

J.

+8  A: 

This is a plain javascript object. Not a jQuery object and not an array.

Accessing properties of an object would work like so:

 $itemPosition.top;
 $itemPosition.left;

Placing a $ as the first character of the name is valid, but may lead to confusion as it is a convention used when storing a jQuery object.

Another valid way to access the properties of your object is to use square brackets, as in:

 $itemPosition['top'];
 $itemPosition['left'];

Using the square bracket method, you can also pass in variables, like so:

var myTopString = 'top';

$itemPosition[myTopString];

If you want to iterate over all the values in your object, you can do the following:

for(var n in $itemPosition) {
    alert( n + ': ' + $itemPosition[n] );
}

This will alert() the key and value of each object property. As you can see, it uses the square bracket method, passing in the key for each property stored in the variable n.

That's all I have to say about that. -F. Gump

patrick dw
+1 - and I would further stress the point that your var should probably be named `itemPosition` not `$itemPosition`. **Most** jQuery code uses the `$` prefix on `$item` as a way of labeling the variable as a jQuery object I.E. - `var $item = $('#theitem");`
gnarf
@gnarf - Indeed. Even in the short example, caught me off guard for a second.
patrick dw
Thanks for this very detailed answer. I have adjusted my script and also removed the `$` symbol which I will from here on out only use for actual jQuery objects. Thanks again.
Jannis
You're welcome. Glad it helped.
patrick dw
+1  A: 

If I'm not mistaken, you can just use properties:

$itemPosition = {
    'top': $item.offset().top,
    'left':$item.offset().left
},

console.log($itemPosition.top);
console.log($itemPosition.left);

All you've done is create a javascript variable called $itemPosition with an anonymous type. It has two properties called top and left.

Damovisa