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?

3
  • Does this answer your question? How to create an associative array in JavaScript literal notation Commented Mar 15, 2021 at 11:12
  • What does unit testing have to do with all of this? Commented Mar 15, 2021 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. Commented Mar 15, 2021 at 11:24

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.