Fell
Fell

Reputation: 135

Creating Tree Object Dynamically from Collection with Keys

I want to dynamically create a nested Tree object based off a collection of objects that can have the levels of the tree specified by a list of keys.

My collection might look like [{a_id: '1', a_name: '1-name', b_id: '2', b_name: '2_name', c_id: '3', c_name: '3_name'}...]

My keys, which correspond to levels of the tree, might look like: ['a', 'b', 'c']

The top-level object has a property called options that stores {key: any, value: any}. All children have the same but it's nested inside of an array called groups that has a group property that references the value of its parent option.

The outputted Tree object I would like would look something like:

{
  id: 'a',
  options: [{ key: '1-name', value: '1'}...],
  child: {
    id: 'b',
    groups: [
      { group: '1', name: '1-name', options: [{key: '2-name', value: '2'}]}
    ],
    child: {
      id: 'c',
      groups: [
        { group: '2', name: '2-name', options: [{key: '3-name', value: '3'}]}
      ],
    }
  }
}

I'm having difficulty writing a succint function that will build this recursive structure off of the basic collection. I basically want the keys to define the nested structure and group the related objects from the original collection as recursive children. If there is a better way to get the original collection into the output structure I'm all ears.

Upvotes: 1

Views: 835

Answers (2)

Fell
Fell

Reputation: 135

I created a class that ingests the whole collection and has the method export to get the data in the format I requested in the original question:

import { Option, OptionGroup, SelectTreeFieldOptions } from '@common/ui';
import { isObject } from 'lodash';

// Symbol used for Key in Group
const KEY_SYMBOL = Symbol('key');

/**
 * Tree class used to create deeply nested objects based on provided 'level'
 */
export class Tree {

  private readonly level: string;
  private readonly groups: Record<string, Record<string, any>>;
  private readonly child?: Tree;

  constructor(private readonly levels: string[], private readonly isRoot = true) {
    this.level = levels[0];
    this.groups = isRoot && { root: {} } || {};
    if (levels.length > 1) {
      this.child = new Tree(levels.slice(1), false);
    }
  }

  /**
   * Set Tree Data with Collection of models
   * Model should have two properties per-level: ${level}_id and ${level}_name
   * Each entry is matched to the level Tree's groups and then passed down to its children
   * @param data - the Collection of data to populate the Tree with
   */
  setData(data: Record<string, any>[]): Tree {
    data.forEach(entry => this.addData(entry, 'root', ''));
    return this;
  }

  export() {
    const key = this.isRoot && 'options' || 'groups';
    const values = this.getOptionsOrGroups();
    return {
      id: `${this.level}s`,
      [key]: values,
      ...(this.child && { child: this.child.toSelectTreeField() } || {}),
    };
  }

  /**
   * Retrieve recursive Option or OptionGroups from each level of the Tree
   * @param nestedObject - optional sub-object as found on a child branch of the Tree
   */
  protected getOptionsOrGroups(nestedObject?: Record<string, any>): (Option | OptionGroup)[] {
    const options = (this.isRoot && this.groups.root) || nestedObject || this.groups;
    return Object.entries(options).map(([val, key]) => {
      const value = Number(val) || val;
      if (!isObject(key)) {
        return { key, value };
      }
      return { value, group: key[KEY_SYMBOL], options: this.getOptionsOrGroups(key) };
    }) as (Option | OptionGroup)[];
  }

  /**
   * Try to add data from a collection item to this level of the Tree
   * @param data - the collection item
   * @param parentId - ID of this item's parent if this Tree is a child
   * @param parentName - label used for the item's parent if this Tree is a child
   */
  protected addData(data: Record<string, any>, parentId: string, parentName: string) {
    const id = data[`${this.level}_id`];
    const name = data[`${this.level}_name`];
    if (!id || !name) {
      throw new Error(`Could not find ID or Name on level ${this.level}`);
    }
    (this.groups[parentId] || (this.groups[parentId] = { [KEY_SYMBOL]: parentName }))[id] = name;
    if (this.child) {
      this.child.addData(data, id, name);
    }
  }
}

Upvotes: 0

ariel
ariel

Reputation: 16140

function process(keys, data, pgroup, pname) {
  if (keys.length == 0) return;
  var key = keys.shift(); // Get first element and remove it from array
  var result = {id: key};
  var group = data[key + "_id"];
  var name = data[key + "_name"];
  var options = [{key: name, value: group}];
  if (pgroup) { // pgroup is null for first level
    result.groups = [{
      group: pgroup,
      name: pname,
      options: options
    }];
  } else {
    result.options = options;
  }
  if (keys.length > 0) { // If havent reached the last key
    result.child = process(keys, data, group, name);
  }
  return result;
}

var result = process (
  ['a', 'b', 'c'],
  {a_id: '1', a_name: '1-name', b_id: '2', b_name: '2_name', c_id: '3', c_name: '3_name'}
);

console.log(result);

Working demo https://codepen.io/bortao/pen/WNvdXpy

Upvotes: 0

Related Questions