Динамическое создание объекта дерева из коллекции с ключами - PullRequest
1 голос
/ 09 марта 2020

Я хочу динамически создать вложенный объект Tree на основе коллекции объектов, для которых уровни дерева могут быть определены в списке ключей.

Моя коллекция может выглядеть как [{a_id: '1', a_name: '1-name', b_id: '2', b_name: '2_name', c_id: '3', c_name: '3_name'}...]

Мои ключи, соответствующие уровням дерева, могут выглядеть так: ['a', 'b', 'c']

У объекта верхнего уровня есть свойство options, в котором хранится {key: any, value: any}. Все дочерние элементы одинаковы, но они вложены в массив с именем groups, который имеет свойство group, которое ссылается на значение его родительского параметра.

Выводимый объект Tree, который я хотел бы, выглядел бы примерно так:

{
  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'}]}
      ],
    }
  }
}

Мне трудно написать функцию succint, которая будет строить эту рекурсивную структуру из коллекции basi c. В основном я хочу, чтобы keys определял вложенную структуру и группировал связанные объекты из исходной коллекции как рекурсивные дочерние элементы. Если есть лучший способ вставить оригинальную коллекцию в структуру вывода, я все уши.

Ответы [ 2 ]

0 голосов
/ 10 марта 2020

Я создал класс, который принимает всю коллекцию и имеет метод export для получения данных в формате, который я запросил в исходном вопросе:

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);
    }
  }
}
0 голосов
/ 10 марта 2020
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);

Рабочая демонстрация https://codepen.io/bortao/pen/WNvdXpy

...