3

I'm curious, is there another way to convert a struct into an array in Coldfusion without looping over it? I know it can be done this way if we use a for in loop:

local.array = [];
for (local.value in local.struct)
{
   arrayAppend(local.array, local.value);
}

3 Answers 3

5

Does StructKeyArray suit your requirements?

Description

Finds the keys in a ColdFusion structure.

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

Comments

2

If you are trying to maintain order in your structure you could always use a Java LinkedHashMap like so:

cfmlLinkedMap = createObject("Java", "java.util.LinkedHashMap").init();

cfmlLinkedMap["a"] = "Apple";
cfmlLinkedMap["b"] = "Banana";
cfmlLinkedMap["c"] = "Carrot";

for(key in cfmlLinkedMap){
    writedump(cfmlLinkedMap[key]);  
}

You could also do the same thing in a more "java" way not sure why you'd want to but its always an option:

//no need to init
linkedMap = createObject("Java", "java.util.LinkedHashMap");

//java way
linkedMap.put("d","Dragonfruit");
linkedMap.put("e","Eggplant");
linkedMap.put("f","Fig");

//loop through values
iterator = linkedMap.entrySet().iterator();        

while(iterator.hasNext()){
    writedump(iterator.next().value);   
}

//or

//loop through keys
iterator = linkedMap.keySet().iterator();

while(iterator.hasNext()){
    writedump(linkedMap.get(iterator.next()));  
}

Just remember that the keys are case SeNsItIvE!

Comments

1

In Coldfusion 10 or Railo 4, if you want an array of values (instead of keys), you can use the Underscore.cfc library like so:

_ = new Underscore();// instantiate the library

valueArray = _.toArray({first: 'one', second: 'two'});// returns: ['one','two']

Note: Coldfusion structures are unordered, so you are not guaranteed to have any specific order for the values in the resulting array.

(Disclaimer: I wrote Underscore.cfc)

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.