Reputation: 93
I lack some basics in these languages so it might be an easy question.
I receive an json encoded array of object from an ajax call. At the begining of it, I add some elements I need :
array_unshift($data, array('nbr' => 6,'Col1' => 'Company name',
'Col2' => 'Email','Col3' => 'Adress','Col4' => 'City',
'Col5' => 'Code','Col6' => 'Country));
In the success:function(msg)
of the ajax I want to iterate through these elements to make them the headers of a table :
var qtt=msg[0].nbr;
$foo='<table>';
for (var i = 1; i<qtt; i++) {
$foo=$foo+'<th>'+msg[i].Col+i+'</th>';
}
$foo=$foo+'</table>;
I want to access the i'th element of msg and I know it is named 'Col'+i. To me, it looks simple and difficult at the same time.
I just don't know how to do this, no idea. Any help is welcome.
Edit : With firebug I could retreive the answer of the ajax call. If it can help you here it is (the element are in french but it is exactly what I was talking about previously) :
[{"nbr":6,"Col1":"Nom soci\u00e9t\u00e9","Col2":"Email","Col3":"Adresse",
"Col4":"Ville","Col5":"Code postal","Col6":"Pays"},
{"Soc_Nom":"foo1","Soc_Email":"bar1","Soc_Adresse":"foobar1", "Vil_Nom":
"Foofoo1","Vil_Code_Postal":"1000","Pys_Nom":"Belgique"},{"Soc_Nom":
"Foo2","Soc_Email":"Bar2","Soc_Adresse":"foobar2","Vil_Nom":"Foofoo2",
"Vil_Code_Postal":"2000","Pys_Nom":"Belgique"}]
Ansewer : No need to iterate through msg[] since all the info I wanted to access was in msg[0].
Using msg[0]['Col'+i] works perfectly.
Upvotes: 0
Views: 33
Reputation: 8495
If you're trying to access a property name dynamically, you can use an indexer with the property name as a string:
$foo=$foo+'<th>'+msg[i].Col+i+'</th>';
becomes
$foo=$foo+'<th>'+msg[i]['Col' + i]+'</th>';
msg[i].Col + i
(your original code) is looking for a property named Col
and trying to add the value of Col
to the value of i
.
The second example is building a dynamic property name 'Col' + i
, and using brackets to access a property of that name on the msg[i]
object.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors
Upvotes: 1