views:

240

answers:

2

Suppose I declare a structured Javascript variable like this:

var mydata = {'list':[
{'fname':'george','lname':'washington'}
,{'fname':'oscar','lname':'wilde'}
,{'fname':'james','lname':'polk'}
]
,'summary':this.list[1]['lname']
}

Question: How can I ensure that

this.list[1]['lname']

equals 'wilde' and that my "this" is actually referring to what I intend?

+2  A: 

this won't work as written, but you could do:

var mydata = {'list':[
{'fname':'george','lname':'washington'}
,{'fname':'oscar','lname':'wilde'}
,{'fname':'james','lname':'polk'}
]
}   

mydata.summary = mydata.list[1]['lname'];
Jonathan Fingland
+4  A: 

You could also make this work in a function.

var mydata = {'list':[
{'fname':'george','lname':'washington'}
,{'fname':'oscar','lname':'wilde'}
,{'fname':'james','lname':'polk'}
]
,'summary':function(){return this.list[1]['lname']}
}

alert(mydata.summary());
Jose Basilio