Combine Like Keys into String

Swiftlikeninja's picture

I have been messing around with a javascript patch that will loop through a structure (about 1000 entries) and parse out the similar keys into single strings. the Code im using is as follows:

function (__structure structureOut) main ( __structure structureIn)
{
   if (!_testMode) {
 
        var Rebuild = new Object();
 
        for(i = 0; i <structureIn.length; i++) {
           Rebuild[structureIn[i][0]] +=structureIn[i][1];
          }
 
           var result = new Object();
           result.structureOut=Rebuild;
          return result;
   }
}

but the end results have an extra 'undefined' entry at the beginning of each new string. Can anyone explain why this is occurring? I've attached a sample compostion to better show.

PreviewAttachmentSize
Combine.qtz13 KB

Swiftlikeninja's picture
Re: Combine Like Keys into String

I ended up adding a loop to create the named structure before parsing any data through it, instead of as I was parsing. This removed the errant undefined. I was always under the assumption that the !_testMode would resolve any undefined issues in this scenario but in any case I appear to have resolved this issue.

   for(i = 0; i <structureIn.length; i++) {
           Rebuild[structureIn[i][0]] =new String();
           }

usefuldesign.au's picture
Re: Combine Like Keys into String

The undefined comes from the fact that you use the += operator to assign a string to a new object item. It adds the string to the previous value, and seeing as that element in the structure doesn't exist when the script first comes to that item key it evaluates as the string "undefined" which it it then ads the first Part to.

If you use the following it will eliminate the problem (I shortened structureIn to In):

              if (Rebuild[In[i][0]])
              {
                 Rebuild[In[i][0]] +=In[i][1];
              } else {
                 Rebuild[In[i][0]] =In[i][1];
              }
PreviewAttachmentSize
Combine i.qtz8.51 KB

usefuldesign.au's picture
Re: Combine Like Keys into String

pls nuke double post