javascript - 如何从具有类别和子类别属性的平面对象数组构建树数组

标签 javascript arrays data-structures

我正在尝试从平面数组构建树形数组,平面数组中的每个项目都有两个属性需要用于构建树形数组,它们是 1. 类别。 2. subCategrie,字符串数组。

let data = [
  {
    id: 1,
    name: "Zend",
    category: "php",
    subCategory: ["framework"]
  },
  {
    id: 2,
    name: "Laravel",
    category: "php",
    subCategory: ["framework"]
  },
  {
    id: 3,
    name: "Vesion 5",
    category: "php",
    subCategory: ["versions"]
  },
  {
    id: 4,
    name: "Angular",
    category: "frontend",
    subCategory: ["framework", "typescript"]
  },
  {
    id: 5,
    name: "Aurelia",
    category: "frontend",
    subCategory: ["framework", "typescript"]
  },
  {
    id: 6,
    name: "JQuery",
    category: "frontend",
    subCategory: []
  }
];

应该是

    let tree = [
      {
        name: "php",
        children: [
          {
            name: "framework",
            children: [
              {
                id: 1,
                name: "Zend"
              },
              {
                id: 2,
                name: "Laravel"
              }
            ]
          },
          {
            name: "versions",
            children: [
              {
                id: 3,
                name: "Vesion 5"
              }
            ]
          }
        ]
      }
 // ...
    ];

有没有解决类似问题的文章,链接? 我尝试了很多次,但在尝试构建子类别子类别时卡住了。

这是我最后一次抛出错误的尝试,我知道这是错误的,但它是为那些想看到我的尝试的人准备的

const list = require('./filter.json')
let tree = {};
for (let filter of list) {
    if (tree[filter.category]) {
        tree[filter.category].push(filter);
    } else {
        tree[filter.category] = [filter];
    }
}
function buildChildren(list, subcategories, category, index) {
    let tree = {}
    for (let filter of list) {
        if (filter.subcategory.length) {
            for (let i = 0; i < filter.subcategory.length; i++) {
                let branch = list.filter(item => item.subcategory[i] === filter.subcategory[i]);
                branch.forEach(item =>{
                    if (tree[filter.subcategory[i]]){
                        tree[filter.subcategory[i]] = tree[filter.subcategory[i]].push(item)
                    }else{
                        tree[item.subcategory[i]] = [item]
                    }
                })
            }
        }
    }

    console.log('tree ', tree);
}

最佳答案

注意,对于 javascript,我通常使用 Lodash (通常在代码中写成 _)但是大多数这些方法也应该内置到 javascript 中的对象中(即 _.forEach = Array.forEach())

    const tree = [];
    // First Group all elements of the same category (PHP, Frontend, etc.)
    data = _.groupBy(data, 'category');
    _.forEach(data, function (categoryElements, categoryName) {
      // Each Category will have it's own subCategories that we will want to handle
      let categorySubCategories = {};
      // The categoryElements will be an array of all the objects in a given category (php / frontend / etc..)
      categoryElements.map(function (element) {
        // For each of these categoryies, we will want to grab the subcategories they belong to
        element.subCategory.map(function (subCategoryName) {
          // Check if teh category (PHP) already has already started a group of this subcategory,
          // else initialize it as an empty list
          if (!categorySubCategories[subCategoryName]) { categorySubCategories[subCategoryName] = []; }
          // Push this element into the subcategory list
          categorySubCategories[subCategoryName].push({id: element.id, name: element.name});
        });
      });
      // Create a category map, which will be a list in the format {name, children}, created from
      // our categorySubCategories object, which is in the format {name: children}
      let categoryMap = [];
        _.forEach(categorySubCategories, function (subCategoryElements, subCategoryName) {
          categoryMap.push({name: subCategoryName, children: subCategoryElements});
        });
      // Now that we've grouped the sub categories, just give the tree it's category name and children
      tree.push({name: categoryName, children: categoryMap});
    });
  };

关于javascript - 如何从具有类别和子类别属性的平面对象数组构建树数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52951768/

相关文章:

php - 在 php 准备语句中从另一个字符串添加到数组

arrays - 复制相同类型的数组

javascript - 通过点击获取元素的id(JS)

javascript - AJAX 请求在 IE8 和 IE9 中不起作用

javascript - "GL_INVALID_OPERATION: Insufficient buffer size."在可变数量的渲染调用之后

javascript - 使用 javascript/jQuery 动态更改内容

c - 在C中初始化结构内部的数组

php - 通过键名仅从 JSON 获取特定键/值,而不是全部

c++ - 关于使用链表在堆栈实现中的嵌套类

algorithm - 在矩阵中的源和目标之间建立路径所需的最少翻转