0

I wanting to replicate this array structure in Javascript, but I cannot figure out how to do it, in my php I have the following,

$myArray = array();
$myArray['location1'] = array('name' => 'Texas', 'person' => 'Jim');  
$myArray['location2'] = array('name' => 'California', 'person' => 'Jeff');  

This would leave me a structure that looks like,

myArray = array(
    'location1' = array('name' => 'Texas', 'person' => 'Jim')
    'location2' = array('name' => 'California', 'person' => 'Jeff')
)

What I wanting in javascript is an array that holds other arrays and the sub arrays are keyed is this possible?

mickmackusa
  • 33,121
  • 11
  • 58
  • 86
Udders
  • 6,340
  • 22
  • 91
  • 164
  • Does this answer your question? [How to create an associative array in JavaScript literal notation](https://stackoverflow.com/questions/37515959/how-to-create-an-associative-array-in-javascript-literal-notation) – Christoph Lütjen Mar 15 '21 at 11:12
  • What does unit testing have to do with all of this? – El_Vanja Mar 15 '21 at 11:14
  • 1
    It isn't possible: JS arrays are not associative. You would need to use an object if you wish to have keys. Assuming that the array is initially generated in PHP (server side) I suggest you use `json_encode` in PHP and parse that (client side) in JS. – Steven Mar 15 '21 at 11:24

1 Answers1

0

As stated by Steven, Javascript Arrays are not associative. However, you can parse an Associative PHP Array as a JSON Object which will led to the same structure when passing from or to Client Side.

P.E In PHP you'd have

$myArray = [
   "tag"=>"property",
   "properties"=>[
        "color"=>"blue",
        "name"=>"A Name"
    ]
];

Then, you return this array as JSON

return json_encode($myArray);

And when you receive it on Javascript you do a JSON Parse with the response

function getMyObject()
{
   // Code for retrieving the JSON From Server

   //End of Code for JSON Retrieval

   const myObject = JSON.parse(response);
}

This will led to an structure such as this in Javascript

console.log(myObject)

>>>>
{
  tag:"property",
  properties:{
    color:"blue",
    name:"A Name"
  }
}

Which you can access with the object.key notation or object[key] in Javascript.

Most of frameworks do this in a transparent way. For example, if you're using Laravel when you return the Array as a response in an API route, it will automatically parse it as a JSON. And then, in a framework such as Angular, the HttpClient will automatically parse the JSON response as a JavaScript object.

Then, in the opposite direction, if you send a object to an Endpoint. It will automatically be converted to a JSON body in the request and parsed by the backend framework.