Convert PHP to JavaScript. Store keys / values ​​in an array

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?

+4
source share
3 answers
 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; 
+1
source

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' }; 
+4
source

Use json_encode () :

 <script> var countries = <?php echo json_encode($countries); ?>; </script> 

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 indicated in other posts.

0
source

All Articles