Can you please help with my problem
I have the following JavaScript object:
var data = {
'rows[0][name]': 'foshka',
'rows[0][tel]': '096',
'rows[0][opt]': 'none'
};
The problem is that i get an error while trying to pass variable as rows index:
var i = 0;
var data = {
'rows['+ i +'][name]': 'one',
'rows['+ i +'][tel]': '096',
'rows['+ i +'][opt]': 'none'
};
Thanks in advance
Mutation Person
30.6k18 gold badges102 silver badges166 bronze badges
-
Why are the property names all strings?Oded– Oded2010年07月22日 13:18:10 +00:00Commented Jul 22, 2010 at 13:18
-
2It is legal syntax, though I have a feeling he is not doing what he thinks he is doing.MooGoo– MooGoo2010年07月22日 13:19:40 +00:00Commented Jul 22, 2010 at 13:19
-
What error are you getting? Is it actually an error, or is data not turning out like you expected?A. Levy– A. Levy2010年07月22日 13:21:41 +00:00Commented Jul 22, 2010 at 13:21
-
See also: stackoverflow.com/questions/2274242/…Andy E– Andy E2010年07月22日 13:28:21 +00:00Commented Jul 22, 2010 at 13:28
2 Answers 2
Your code has to be
var data = {};
data[ 'rows['+ i +'][name]' ] = 'one';
data[ 'rows['+ i +'][tel]' ] = '069';
However you might want to change your structure to sth like this:
var data ={};
var i = 0;
data['rows'][i]['name'] = 'one';
Or even cleaner:
var data = { rows[] };
var i = 0;
data['rows'][i] = { 'name' : 'one', 'tel' : 069' };
// so you can access them like this:
alert ( data['rows'][i]['name'] );
answered Jul 22, 2010 at 13:19
jantimon
38.5k23 gold badges127 silver badges196 bronze badges
Sign up to request clarification or add additional context in comments.
3 Comments
Andy E
The second structure will throw an error unless
data['rows'] and data['rows'][i] are defined first.Skilldrick
Please change it into option two - currently it's a crime against programming :)
MooGoo
There's no requirement to use bracket notation to define crazy object properties. Only when accessing said properties is it necessary.
I think your data should look like this:
var data = {
rows: [{
name: 'one',
tel: '096',
opt: null
}]
};
That way you can simply add new rows if needed.
answered Jul 22, 2010 at 13:20
Wolph
80.4k12 gold badges142 silver badges152 bronze badges
Comments
lang-js