0

I have this code:

  var deptDictionary={
           <?php foreach($dept as $cd){
            echo '"'.$cd->department_id.'":"'.$cd->department_name.'",';
            }
           ?>
  }; 

which outputed this:

'Object {1: "ACCOUNTING", 5: "HUMAN RESOURCES", 6: "DEVELOPERS", 15: "ENGINEERING", 23: "ASDASD", 26: "QWEQWE"} '

now, I want to find the index of ACCOUNTING by just inputting the data it points to.

[what's that part called anyway if index is the first part of assoc array?]

I have tried this:

console.log(deptDictionary["accounting"]);

but it returned undefined. Am I missing something? Is there any reading material that points to js assoc array?

EDIT: OK. I have reversed the key and the data, to fit my needs. now it looks like this:

  var deptDictionary={
           <?php foreach($dept as $cd){
            echo '"'.$cd->department_name.'":"'.$cd->department_id.'",';
            }
           ?>
  }; 

But I am still raising this question for future reference, if some other guy finds it important to find the key.

3 Answers3

2

Try this out: http://jsfiddle.net/agconti/j5sX2/; (code below)

// this doesnt work
var dict = {1: "ACCOUNTING", 5: "HUMAN RESOURCES", 6: "DEVELOPERS"};
alert(dict[1]);
alert(dict["ACCOUNTING"]);

//but this will
var dict = {"ACCOUNTING": 1, "HUMAN RESOURCES":5};
alert(dict[1]);
alert(dict["ACCOUNTING"]);
agconti
  • 17,780
  • 15
  • 80
  • 114
0

Remember that its case-sensitive. If your output is like

'Object {1: "ACCOUNTING", 5: "HUMAN RESOURCES", 6: "DEVELOPERS", 15: "ENGINEERING", 23: "ASDASD", 26: "QWEQWE"} '

Then you should use

console.log(deptDictionary["ACCOUNTING"]);

Please verify what is your key? department_name or department_id in echo '"'.$cd->department_name.'":"'.$cd->department_id.'",';

itsazzad
  • 6,868
  • 7
  • 69
  • 89
0

It will be better if you make an array and convert that in a JSON using json_encode() and to access that JSON object statically then you can call the way you were trying,

Ex.deptDictionary["accounting"]

OR

you can also access that using
deptDictionary[Object.keys(deptDictionary)[0]]

Thanks

NickCoder
  • 1,504
  • 2
  • 23
  • 35
Labib
  • 51
  • 1