alega
alega

Reputation: 21

pass variable into javascript object

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

Upvotes: 2

Views: 6403

Answers (2)

jantimon
jantimon

Reputation: 38140

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'] );

Upvotes: 4

Wolph
Wolph

Reputation: 80031

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.

Upvotes: 2

Related Questions