1

This is some data being returned by an API. I need to loop over the arrays that are contained within the nested structure. For example in the image below the savedMajorIds:

enter image description here

isArray(apiprofile.result.savedMajorIds)

returns Yes, so I'm pretty sure it's looking at the right thing. However, when I try to loop over it to get the values it breaks. Code is:

for (i=1, i < arrayLen(apiprofile.result.savedMajorIds),i=i+1) {
        writeOutput(apiprofile.result.savedMajorIds[i]);
    }

Error log doesn't like the arrayLen() portion but so far I've been unable to get that to work.

1
  • What version of ColdFusion? Commented Oct 26, 2018 at 15:29

2 Answers 2

4

For anyone else who stumbles on this:

(i=1, i < arrayLen(apiprofile.result.savedMajorIds),i=i+1)

needs to be

(i=1; i < arrayLen(apiprofile.result.savedMajorIds); i=i+1)

or

(i=1; i < arrayLen(apiprofile.result.savedMajorIds); i++)
Sign up to request clarification or add additional context in comments.

2 Comments

(He replaced comma , with semicolon ;.)
For future reference, you can also use the foreach-syntax: for (id in apiprofile.result.savedMajorIds) { }
3

Here are a few options, depending on your version of ColdFusion.

if (isArray(apiprofile.result.savedMajorIDs)) {
    // For/In Loop on Array - Possibly CF9, Definitely CF10+ (Verify version) 
    // Note: x will leak unless var'ed inside function.
    for ( x IN apiprofile.result.savedMajorIDs ) {
        writeoutput( x & "<br>" ) ;
    }

    // ArrayEach - CF10+ > Note: y will not leak.
    ArrayEach(apiprofile.result.savedMajorIDs, function(y){writeoutput(y & "<br>");}) ;

    // Member Function .each() - CF11+  > Note: z will not leak.
    apiprofile.result.savedMajorIDs.each( function(z){writeoutput(z & "<br>");}) ;
}

https://trycf.com/gist/f6f3e64635e4b72da15521a3d49d485f/acf11?theme=monokai

1 Comment

Doing some testing with various methods, the for/in loop seems to be significantly faster than other methods. That holds for Lists, Arrays, Structs and especially Queries.

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.