Reputation:
I am trying to create an array in javascript which will allow me to access data like this:
var name = infArray[0]['name'];
however I cant seem to get anything to work in this way. When i passed out a assoc array from php to javascript using json_encode it structured the data in this way. The reason why i have done this is so i can pass back the data in the same format to php to execute an update sql request.
Upvotes: 1
Views: 2270
Reputation: 71
JavaScript do not have 2D associative array as such. But 2d associative array can be realized through below code:
var myArr = { K1: {
K11: 'K11 val',
K12: 'K12 Val'
},
K2: {
K21: 'K21 Val',
K22: 'K22 Val'
}
};
alert(myArr['K1']['K11']);
alert(myArr['K1']['K12']);
alert(myArr['K2']['K21']);
alert(myArr['K2']['K22']);
Upvotes: 0
Reputation: 17865
simply var infArray = [{name: 'John'}, {name: 'Greg'}]
;-)
Upvotes: 2
Reputation: 12577
JavaScript doesn't have assoc arrays. Anything to any object declared as obj['somthing']
is equal to obj.something
- and it is a property. Moreover in arrays it can be a bit misleading, so any added property won't changed array set try obj.length
.
Upvotes: 0
Reputation: 227280
JavaScript doesn't have associative arrays. It has (numeric) arrays and objects.
What you want is a mix of both. Something like this:
var infArray = [{
name: 'Test',
hash: 'abc'
}, {
name: 'something',
hash: 'xyz'
}];
Then you can access it like you show:
var name = infArray[0]['name']; // 'test'
or using dot notation:
var name = infArray[0].name; // 'test'
Upvotes: 4