copy Nested Structures / Objects in Javascript

M.Oostrik's picture

Hi

I'm trying to copy a nested structure in the Javascript patch so i can manipulate it. The function i came up with does work, but it messes up the order of the structure.

function cloneObject(oldObject) {
 
   var newObject = new Object()
 
     for (i in oldObject) {
      if (typeof oldObject[i] == 'object') {
         newObject[i] = new cloneObject(oldObject[i]);
      }
      else newObject[i] = oldObject[i];
    }
    return newObject
}

Anyone has a suggestion? i'm kinda at the end of my javascript knowledge here. thanx

toneburst's picture
Re: copy Nested Structures / Objects in Javascript

You should use an Array() rather than an Object(), if the order of items is important.

a|x

M.Oostrik's picture
Re: copy Nested Structures / Objects in Javascript

Thanx!

I ended up making a second function that sorts an Object into an Array:

// This restores the index of an Array mutulated by __Structure 
function arrayFromObject(theObject){
   var SortedArray = [];
   var Count = 0;
   for (e in theObject) Count++; 
   for (i=0; i<Count; i++) {
      SortedArray.push(theObject[i.toString()]);
   }
   return SortedArray;
}

These functions can be helpfull when using the File Tools (structure to/from file patch )