Pak Ho Cheung
Pak Ho Cheung

Reputation: 1426

initialize an empty dictionary in an empty dictionary - Javascript

I want to pass a variable (dict) to server with php code. The variable is a dictionary inside a dictionary and inside a dictionary.

In Swift and Java, I can do write it that way

Swift: var pageDict = [String: [String: [String: Int]]]()

Java: Map<String, Map<String, Map<String, Integer>>> pageDict = new HashMap<>();

EDIT

If I initialize the dict something like this in Javascript [[[]]] , I receive this error

<b>Warning</b>:  array_keys() expects parameter 1 to be array, null given in <b>test.php</b> on line <b>166</b><br />
<br />
<b>Warning</b>:  in_array() expects parameter 2 to be array, null given in <b>test.php</b> on line <b>166</b><br />
<br />

In line 166 (Server Code)

line165 function getExistData($pageDict, $location) {
line166     return in_array($location, array_keys($pageDict)) ? $pageDict[$location] : array();
line167 }

If I try to do it that way, var pageDict = {"____": {"____": {"____": 1}}}; everything works prefect. But this definitely is not a prefect way to do it

Wondering how can I do it in Javascript?

Upvotes: 0

Views: 3341

Answers (1)

Sandesh Gupta
Sandesh Gupta

Reputation: 1195

You can use the following structure to store 3 level multimap.

var mapLevel1 = new Object(); // innermost map
mapLevel1[String1] = Int1;
mapLevel1[String2] = Int2;

var mapLevel2 = new Object(); 
mapLevel2[String3] = map1;

var mapLevel3 = new Object(); //outermost map
mapLevel3[String3] = map2;

Edit: As suggested by @CertainPerformance, convert to string using JSON.stringify before passing data to server.

Upvotes: 1

Related Questions