views:

14893

answers:

6

Simple, quick, question.

How can I create dynamically create keys in javascript associative arrays? All the doc I've found so far is to update keys that are already created:

 arr['key'] = val;

I have a string like this " name = oscar "

And I want to endup with something like this:

{ name: 'whatever' }

That is I split the string and get the first element, and I want to put that in a dict ( asoc arr ).

EDIT

This is what I have and currently doesn't work ( I guess :S )

var text = ' name = oscar '
var dict = new Array();
var keyValuePair = text.split(' = ');
dict[ keyValuePair[0] ] = 'whatever';
alert( dict ); // prints nothing.

EDIT 2

Aaarggg. I hate re-take a programming languages. I forget the most basic things. It turns out I was filling the dict correctly but didn't knew how to display the values :-B . ... . Thank you all

+1  A: 

Use the first example. If the key doesn't exist it will be added.

var a = new Array();
a['name'] = 'oscar';
alert(a['name']);

Will pop up a message box containing 'oscar'.

Try...

var text = 'name = oscar'
var dict = new Array()
var keyValuePair = text.replace(/ /g,'').split('=');
dict[ keyValuePair[0] ] = keyValuePair[1];
alert( dict[keyValuePair[0]] );
tvanfosson
I was doing exactly that ( or though ) but does not work.
OscarRyz
I ran that as a sample in Firefox just to be sure. Did you make sure to put 'name' in quotes?
tvanfosson
Uhmm nope, because, I'm creating the key "dynamically" not statically. Let me doublecheck anyway :)
OscarRyz
Please refer to Danny's more complete explanation. You won't be able to refer to the array values in a for loop with an index (such as myarray[i]). Hope that's not too confusing.
MK_Dev
+1  A: 

Just a reminder: you won't be able to iterate through the values when adding them in this manner. Looking at your question I am pretty sure you knew this (since you want it to use it as "{ name: 'whatever' }"), but some people may not be aware of this.

MK_Dev
Actually I don't. What was that again? :S
OscarRyz
+3  A: 

In response to MK_Dev, one is able to iterate, but not consecutively. (For that obviously an array is needed)

Quick google search brings up hash tables in javascript

Example code for looping over values in a hash (from aforementioned link):

var myArray = new Array();
myArray['one'] = 1;
myArray['two'] = 2;
myArray['three'] = 3;

// show the values stored
for (var i in myArray) {
    alert('key is: ' + i + ', value is: ' + myArray[i]);
}
Danny
+2  A: 

Javascript does not have associative arrays, it has objects.

The following lines of code all do exactly the same thing - set the 'name' field on an object to 'orion'.

var f = new Object(); f.name = 'orion';
var f = new Object(); f['name'] = 'orion';
var f = new Array(); f.name = 'orion';
var f = new Array(); f['name'] = 'orion';
var f = new XMLHttpRequest(); f['name'] = 'orion';

It looks like you have an associative array because an Array is also an Object - however you're not actually adding things into the array at all, you're setting fields on the object.

Now that that is cleared up, here is a working solution to your example

var text = '{ name = oscar }'
var dict = new Object();

// Remove {} and spaces
var cleaned = text.replace(/[{} ]/g, '');

// split into key and value
var kvp = cleaned.split('=');

// put in the object
dict[ kvp[0] ] = kvp[1];
alert( dict.name ); // prints oscar.
Orion Edwards
Assuming the text string actually does have the curly braces, you could more or less treat it as JSON.. replace the = sign with a : and you've got an object to eval..
neonski
Ooops, the string isn't delimited properly. Nothing regex can't fix.
neonski
+23  A: 

Somehow all examples, while work well, are overcomplicated:

  • They use new Array(), which is the overkill (and the overhead) for a simple associative array (AKA dictionary).
  • The better ones use new Object(). Works fine, but why all this extra typing?

This question is tagged "beginner", so let's make it simple.

The uber-simple way to use a dictionary in JavaScript or "Why JavaScript doesn't have a special dictionary object?":

// create an empty associative array (in JavaScript it is called ... Object)
var dict = {};   // huh? {} is a shortcut for "new Object()"

// add a key named fred with value 42
dict.fred = 42;  // we can do that because "fred" is a constant
                 // and conforms to id rules

// add a key named 2bob2 with value "twins!"
dict["2bob2"] = "twins!";  // we use the subscript notation because
                           // the key is arbitrary (not id)

// add an arbitrary dynamic key with a dynamic value
var key = ..., // insanely complex calculations for the key
    val = ...; // insanely complex calculations for the value
dict[key] = val;

// read value of "fred"
val = dict.fred;

// read value of 2bob2
val = dict["2bob2"];

// read value of our cool secret key
val = dict[key];

// change the value of fred
dict.fred = "astra";
// the assignment creates and/or replaces key-value pairs

// change value of 2bob2
dict["2bob2"] = [1, 2, 3];  // any legal value can be used

// change value of our secret key
dict[key] = undefined;
// contrary to popular beliefs assigning "undefined" does not remove the key

// go over all keys and values in our dictionary
for(key in dict){
  // for-in loop goes over all properties including inherited properties
  // let's use only our own properties
  if(dict.hasOwnProperty(key){
    console.log("key = " + key + ", value = " + dict[key]);
  }
}

// let's delete fred
delete dict.fred;
// fred is removed, the rest is still intact

// let's delete 2bob2
delete dict["2bob2"];

// let's delete our secret key
delete dict[key];

// now dict is empty

// let's replaced it recreating all original data
dict = {
  fred:    42,
  "2bob2": "twins!"
  // we can't add the original secret key because it was dynamic,
  // we can only add static keys
  // ...
  // oh well
  temp1:   val
};
// let's rename temp1 into our secret key:
if(key != "temp1"){
  dict[key] = dict.temp1; // copy the value
  delete dict.temp1;      // kill the old key
}else{
  // do nothing, we are good ;-)
}
Eugene Lazutkin
+1  A: 

Original Code (I added the line numbers so can refer to them):

1 var text = ' name = oscar '

2 var dict = new Array();

3 var keyValuePair = text.split(' = ');

4 dict[ keyValuePair[0] ] = 'whatever';

5 alert( dict ); // prints nothing.

Almost there... - line 1: you should do a 'trim' on text so it is 'name = oscar'. - line 3: okay as long as you ALWAYS have spaces around your equal. might be better to not 'trim' in line 1, use '=' and trim each keyValuePair - add a line after 3 and before 4: key = keyValuePair[0]; - line 4: Now becomes: dict[key] = keyValuePair[1]; - line 5: Change to: alert( dict['name'] ); // it will print out 'oscar'

What I'm trying to say is that the dict[keyValuePair[0]] does not work, you need to set a string to keyValuePair[0] and use that as the associative key. That is the only way I got mine to work. After you have set it up you can either refer to it with numeric index or key in quotes.

Hope that helps.

Andrea