0

Im currently using jQuery to build an Array like this:

var arr = new Array();
   $('#some-form .some-input').each(function() {
   arr.push($(this).val());                                                                                                                    
});

which builds something like:

arr[0] = 'bar'
arr[1] = 'foo'

Now I want a data structure (a 'map'? a JSON array?) to do get something like this:

{ 'key1' : 'foo'
  'key2' : 'bar' }

because I am now going to store multiple 'things' from $('#some-form .some-input').

In C, I think this could be a linked list because you don't know how big the data structure will be in advance so you wouldn't use an array. However, I AM using an array here which might not be the best idea? What's sort of structure do I need?

Many thanks.

ale
  • 11,636
  • 27
  • 92
  • 149

1 Answers1

3

With javascript you can dynamically add properties to an object, so you can do something like this:

var arr = {};
$('#some-form .some-input').each(function() {
    var $this = $(this);
    arr[$this.attr('id')] = $this.val();
});

And you can access them with arr.key1; // foo

Edit: as the comments below note, you can also access the values using the [] notation, like arr['key2'] // bar (thanks for reminding me :))

Laurence
  • 1,673
  • 11
  • 16
  • 2
    You should add a note that you can also access them with bracket notation – Shmiddty Oct 22 '12 at 19:15
  • To be extra clear, In javascript, all objects are essentially just maps. If you want a map you can just instantiate a new object and use that as your map. Both dot and [] syntax work for lookup. – Herms Oct 22 '12 at 19:15
  • @Laurence that's fine but is it efficient? You're dynamically adding values and you're dynamically adding keys.. it could be fine but I don't know! Thanks +1. – ale Oct 22 '12 at 19:16
  • 1
    I just found this question which has a very detailed performance run-down you might find useful: http://stackoverflow.com/questions/8423493/what-is-the-performance-of-objects-arrays-in-javascript-specifically-for-googl – Laurence Oct 22 '12 at 19:23