преобразование плоского объекта во вложенную иерархию в javascript - PullRequest
0 голосов
/ 19 апреля 2020

Я пытаюсь преобразовать из плоской структуры во вложенную иерархию. isFilterNode prop определяет, является ли он родительским фильтром. Если он установлен на false, то этот узел вставляется в некоторый родительский узел. Каждое значение фильтра имеет parentFilterCategoryCode, которое определяет, каков родительский его узел. Я приложил код, и он работает нормально, но могу ли я улучшить производительность во время выполнения.

И как я могу написать функцию, которая будет делать противоположное без recursion?

const input = {
  p_pState: {
    isFilterNode: true,
    filterValues: [{
        value: {
          code: 'AL'
        },
        parent: null,
        parentFilterCategoryCode: null,
        subFilters: []
      },
      {
        value: {
          code: 'AK'
        },
        parent: null,
        parentFilterCategoryCode: null,
        subFilters: []
      }
    ]
  },
  p_pCity: {
    isFilterNode: false,
    filterValues: [{
        value: {
          code: 'USA - AL - AnyTown'
        },
        parent: 'AL',
        parentFilterCategoryCode: 'p_pState',
        subFilters: []
      },
      {
        value: {
          code: 'USA - AL - Auburn'
        },
        parent: 'AL',
        parentFilterCategoryCode: 'p_pState',
        subFilters: []
      }
    ]
  },
  p_pworklocation: {
    isFilterNode: false,
    filterValues: [{
        value: {
          code: 'ZPAL'
        },
        parentFilterCategoryCode: 'p_pCity',
        parent: 'USA - AL - AnyTown',
        subFilters: []
      },
      {
        value: {
          code: 'STAL2'
        },
        parentFilterCategoryCode: 'p_pCity',
        parent: 'USA - AL - Auburn',
        subFilters: []
      },
      {
        value: {
          code: 'RTPAL'
        },
        parentFilterCategoryCode: 'p_pState',
        parent: 'AK',
        subFilters: []
      }
    ]
  }
};
const convertMapToHierarchy = (filterValueMap: any): any => {
  const filters = [];

  Object.keys(filterValueMap).forEach((filterkey: any) => {
    const filterMap = filterValueMap[filterkey];

    if (filterMap.isFilterNode) {
      filters.push(filterMap);
    } else {
      const parentCategoryCodes = new Set(
        filterMap.filterValues.map(
          filterValue => filterValue.parentFilterCategoryCode
        )
      );
      parentCategoryCodes.forEach((parentFilterCategoryCode: string) => {
        const parent = filterValueMap[parentFilterCategoryCode];
        if (parent && parent.filterValues) {
          parent.filterValues.forEach(parentFilterValue => {
            const subFilter = {
              itemID: filterMap.itemID,
              filterCategoryCode: filterMap.filterCategoryCode,
              filterValues: filterMap.filterValues.filter(
                filterValue =>
                filterValue.parent === parentFilterValue.value.code
              )
            };
            if (subFilter.filterValues.length > 0) {
              parentFilterValue.subFilters.push(subFilter);
            }
          });
        }
      });
    }
  });

  return filters;
};

console.log(convertMapToHierarchy(input));
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...