I need help with some arrays in JavaScript.

What I would like to do is something like this:

data=new array(
key => value,
key2 => value2,
key3 => value3,
...)

I don't know if its possible to do it in a similar way as you would do it in PHP.

I need to assign multiples key and values from a string in just one code line; I mean, in a simple way without using some kind of loop or something like that.

I'm trying without success with:

valor = "{'name':'facu','id':'12434'}";
ar = eval(valor);
name = ar['name'];
dni = ar['id'];

Edit

Thanks the people who answer, the problem is that the value of my var valor is assigned by a string returned by ajax... what I have is that, and in data I will receive a string like "{'name':'facu','id':'12434'}", so I need to assign that info to an array.

$.get("gestorAjax.php", { funcion: 'getAfiliado', legAfiliado: legAfiliado} ,  function(data){
    valor = eval(data)
});
share|improve this question
4  
Please read some introductory material about JavaScript and objects: developer.mozilla.org/en/JavaScript/Guide/… – Felix Kling May 6 '12 at 18:10
1  
please don't ever use eval. stackoverflow.com/questions/86513/… – Thomas Jones May 6 '12 at 18:14
Use getJSON instead of get. Then jQuery will decode the JSON data for you. – bažmegakapa May 6 '12 at 18:32

3 Answers

in JavaScript this isn't so much an array as it is an object but it would be something along the lines of

var data = {
key: value,
key2: value2
}

then you can do data[key] to get value

share|improve this answer

Never use eval.

var data = 
{
'key'  : value,
'key2' : value2,
'key3' : value3
}

data is an js object not an array, but you can use it in your case (as hash keys),

e.g.

data.key or data[key] will give value.

p.s. Notice that value3 does not have an , (commma). Unlike php, its not optional

share|improve this answer

I think simple javascript Object may me used here, i.e.:

var data = {
    key: 'value',
    key2: 'value2',
    keyN: 'valueN'
};

So, you can use it then as data.key or data['key'] and loop as

for (var key in data) {
    data[key];
}

For parsing obect from JSON request you may use JSON.parse function:

var data = JSON.parse('{"key1":"val1","key2":"val2","key3":"val3"}');

and then again use as data.key1 or data['key1']

share|improve this answer

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.