What's new

Web Unflatten JS

  • Thread starter NukeZilla
  • Start date
  • Views 230
N

NukeZilla

Enthusiast
Messages
144
Reaction score
40
So I've been working on an in memory dom and also a flatten menu structure which required structuring. So i wrote this independent function that doesn't require any third party libraries such as loaddash or underscore.
Code:
function unflatten(arr, options= {}) {
    options.id = options.id || 'id';
  options.parent = options.parent || 'parentId';
  options.children = options.children || 'children';
  for(let index = arr.length - 1; index >= 0; index-- ) {
      if(arr[index][options.parent] === null) {
        continue;
    }
    
    let parent = arr.find((x) => { return x[options.id] == arr[index][options.parent]});
    
    if(parent === undefined) {
        continue;
    }
    
    parent[options.children] = parent[options.children] || [];
    parent[options.children].push(arr[index]);
    
    arr.splice(index, 1);
  }
  return arr;
}
export {unflatten}

Kind regards,
Jordan
 
Top Bottom