views:

30

answers:

3

How can I access the key of a non-associate array? Here's my scenario, I have an array of objects (in this case, they are coordinates):

coords[0] = {x: 37.543524, y: -56.65474}
coords[1] = {x: 35.041292, y: -76.03135}
//etc.. 

I'm using a jQuery templating plugin to print out the results:

$('#repeater').tmpl(coords).appendTo('body');

<script id="repeater" type="text/html">
  <p>[${key??}] ${x}, ${y}</p><br/>
</script>

In the template, I have access to the object properties but not the index. Is there an easy way to retrieve the key of that object in the array? Or would I have to modify the plug-in to give me access to it?

Thanks!

A: 
JapanPro
I know this is redundant, but there is no way to access the key from the value? coords[0].key // is 0. There's no hidden properties or anything that I'm missing? Functions can always be referred back via arguments.callee, wasn't sure if arrays had something similar in nature.
John Strickler
@John no, coords[0] isn't aware of it's position in the parent array. You'd either need to massage the data or calculate it in your template. I posted a solution that suggests the first option.
BBonifield
its the same code i have added, dont know what make you wrong?
JapanPro
A: 
function index( item, array ) {
    return $.inArray( item, array ) + 1;
}

$('#repeater').tmpl({coords: coords}).appendTo('body');

<script id="repeater" type="text/html">
  {{ each coords }}
  <p>[${index($value, coords)}] ${x}, ${y}</p><br/>
  {{ /each }}
</script>

Derived from this example

sje397
This looks like it should work, for some reason the plugin isn't iterating as it should though. I'll test it some more, thanks for your help! Very crafty!
John Strickler
@John Strickler - did you notice the change to the data passed in to the template? `{coords: coords}`
sje397
Yea, you tackled the problem really well actually :p I went with 'massaging' the data since it worked for what I needed. If I needed something more exact then I would have gone what you suggested. I didn't spend much time trying to get it going but tomorrow I think I'll take another stab at it!
John Strickler
A: 

I don't believe that plugin gives you access to that information, so I'd suggest you just massage your data to include it.

So if coords is already set as you mentioned, just loop over it and add a 'key' property to each item.

for( var key in coords ) {
   coords[ key ].key = key;
}

Then you can use the ${key} property in your templates.

BBonifield
That's what I think I'm going to do even though its a work around to the problem :) coords.push({ key: coords.length, x: xVal, y: yval });
John Strickler