ngplayground
ngplayground

Reputation: 21667

Converting PHP to JavaScript. Store keys/values into 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's the best way to do this in jQuery or JavaScript?

Upvotes: 4

Views: 583

Answers (3)

moonwave99
moonwave99

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

Jo&#227;o Silva
Jo&#227;o Silva

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

Andreas Wong
Andreas Wong

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

Related Questions