Web Unflatten JS

Discussion in 'Source Code & Tutorial Database' started by NukeZilla, Jan 10, 2017 with 0 replies and 165 views.

  1. NukeZilla

    NukeZilla Premium Premium

    Messages:
    144
    Ratings:
    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
     

Share This Page