Search code examples
javascriptarrayscoldfusioncfmlcoldfusion-2016

looping with for ( in ) on Javascript does not match ColdFusion


In ColdFusion, I can do this

<cfscript>
  favorites = [{"broker_label":"spectra"}]; 

  for (afav in favorites)   {
    writedump(afav);
  }
</cfscript>

And I get each row in the array.

If I try this in Javascript

favorites = [{"broker_label":"spectra"}];   

for (var afav in favorites) {
  console.log(JSON.stringify(afav));
}

And all I get is 0, or to be exact. "\"0\""

What is going on?


Solution

  • If you want to iterator over the values of an array you can use for…of or array.forEach()

    favorites = [{"broker_label":"spectra"}]; 
    
    for (let fav of favorites)   {
                console.log(JSON.stringify(fav));
    }
    
    // or:
    
    favorites.forEach(elem => console.log(JSON.stringify(elem)))

    for…in iterates over the properties which in the case of arrays is the indexes. Note that using for…in with arrays is discouraged when order is important:

    From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in:

    Note: for...in should not be used to iterate over an Array where the index order is important.