Search code examples
autohotkey

AHKV1: How to get a long string that consists of values tht a associative array holds?


obj                     := {}
obj.kevin               :=  {}
obj.kevin.fullname  :=  "John Smith"
obj.kevin.age           :=  50

obj.hellen              :=  {}
obj.hellen.fullname := "Hellen Smith"
obj.hellen.age          := 60

obj.tim                 :=  {}
obj.tim.fullname        := "Tim Smith"
obj.tim.age             := 30

Lets say I have an object like the above. I want to take the fullname value of every sub object and concatenate it to form a long string:

John SmithHellen SmithTim Smith

I thought I could do it with a simple loop:

Loop,% obj
        str += obj[A_Index].fullname

ConsoleX(str) ; "John SmithHellen SmithTim Smith"

But apparently associate arrays don't support bracket indexing [] like simple arrays do (MyArray[3]), something I was under the impression that they did. Associate arrays allow for obj["time"] but I am not sure what I can do with that in this case.

I thought of using a loop to do this because I figured it is the quick and dirty way, is there an actually built in facility for doing this?

It is a very common thing to do. For example enumerate all of the values of a property a object has, and maybe join them into a string. I do this all of the time elsewhere such as PowerShell.

Thanks for any help.


Solution

  • You can just use a simple for loop(docs):

    obj := { "hellen": { "age": 60, "fullname": "Hellen Smith" }
           , "kevin":  { "age": 50, "fullname": "John Smith"   }
           , "tim":    { "age": 30, "fullname": "Tim Smith"    } }
    
    
    for each, person in obj
        str .= person.fullname ", "
    
    MsgBox, % RTrim(str, ", ")
    

    Also, in AHK + doesn't concatenate strings. It's for adding numbers.
    . is the concatenation operator.