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 is the best way to do this in jQuery or JavaScript?
var countries = { "AF": "AFGHANISTAN", "AX": "ALAND ISLANDS" }
Then, to get the value for the given key, use one of the following values:
var af = countries["AF"]; var ax = countries.AF;
javascript does not have an associative array (as in PHP, your example above), instead we call it a javascript object:
var countries = { 'AF': 'AFGHANISTAN', 'AX': 'ALAND ISLANDS' };
Use json_encode () :
<script> var countries = <?php echo json_encode($countries); ?>; </script>
What will be stored in countries :
countries
{ AF : "AFGHANISTAN", AX : "ALAND ISLANDS" }
If you just want to reproduce such a data structure in JS, use objects as indicated in other posts.