1

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.

4
  • 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. Commented Aug 5, 2013 at 18:47
  • @DevlshOne: JSON is a serialization format also, just a different one. Commented Aug 5, 2013 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? Commented Aug 5, 2013 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. Commented Aug 5, 2013 at 18:49

4 Answers 4

4

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'
Sign up to request clarification or add additional context in comments.

2 Comments

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 ?
Glad I could help! :-D
2

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

Comments

0

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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.