Reputation: 21667
I want to convert the following PHP code to JavaScript, This is an array of key/value pairs in PHP:
PHP code:
$countries = array("AF"=>"AFGHANISTAN","AX"=>"ALAND ISLANDS");
What's the best way to do this in jQuery or JavaScript?
Upvotes: 4
Views: 583
Reputation: 22820
Use json_encode():
<script>
var countries = <?php echo json_encode($countries); ?>;
</script>
That's what will be stored in countries
:
{
AF : "AFGHANISTAN",
AX : "ALAND ISLANDS"
}
If you just want to reproduce such a data structure in JS, use objects as stated in the other posts.
Upvotes: 0
Reputation: 91349
var countries = {
"AF": "AFGHANISTAN",
"AX": "ALAND ISLANDS"
}
Then, to get the value for a given key, use one of the following:
var af = countries["AF"];
var ax = countries.AF;
Upvotes: 1
Reputation: 60594
javascript doesn't have an associative array (like in PHP, your example above), instead, we call it javascript object:
var countries = {
'AF': 'AFGHANISTAN',
'AX': 'ALAND ISLANDS'
};
Upvotes: 4