Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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.

share|improve this question
    
If you just serialize the array, pass it to the other PHP file and then unserialize it, you will have an easier time of it. The intermediate Javascript conversion doesn't seem necessary. –  DevlshOne Aug 5 '13 at 18:47
    
@DevlshOne: JSON is a serialization format also, just a different one. –  Rocket Hazmat Aug 5 '13 at 18:48
    
I don't quite understand what you mean, I have 2 arrays containing information which i need to pass back into php with the id from the information array taken out of php? –  Jack Taylor Aug 5 '13 at 18:48
    
@RocketHazmat. I know what JSON is. LOL. If he's just sending it to another PHP file to process it in the database, there's no reason to make a Javascript Object out of it. –  DevlshOne Aug 5 '13 at 18:49

3 Answers 3

up vote 0 down vote accepted

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'
share|improve this answer
    
Thank you so much for all your answers, have been stuck stupidly on this for too long (guess sleep is needed) How would you do this so its empty and then you can populate it in a for loop ? –  Jack Taylor Aug 5 '13 at 19:01
    
Glad I could help! :-D –  Rocket Hazmat Aug 5 '13 at 19:01

simply var infArray = [{name: 'John'}, {name: 'Greg'}] ;-)

share|improve this answer

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.