将与10位数密钥相关的项目分组?

时间:2018-05-02 11:41:50

标签: javascript

    This has to be grouped using logic since it has large number of item.statically giving values using j query wont work for me.

这是一系列项目。基于ID我需要以树的形式格式化它

    [{"ID":"0200000000", "Name":"a"},
     {"ID":"0201000000", "Name":"b"},
     {"ID":"0201010000", "Name":"c",},
     {"ID":"0201010100", "Name":"d", },
     {"ID":"0201010200", "Name":"e",},
     {"ID":"0201010300", "Name":"f",},
     {"ID":"0300000000", "Name":"g"},
     {"ID":"0301000000", "Name":"h"},
     {"ID":"0301010000", "Name":"i"},
     {"ID":"0301010100", "Name":"j"},
     {"ID":"0301010200", "Name":"k"},
     {"ID":"0301010300", "Name":"l"},
     {"ID":"0301010400", "Name":"m"},
     {"ID":"0400000000", "Name":"n"}]

    This should be the result.It is based on the ID from the array.
   I am using j query in front end and java script in back end   
    -a
       -b
          -c
          -d
          -e
          -f
    -g
       -h
          -i
          -j
          -k
          -l    
          -m
    -n




  for (i = 1; i < 14; i++) {
      item2[i] = resultArray1[i]
      item5[i] = resultArray[i + 1]
      item[i] = resultArray1[i].split("", 10);
      item1[i] = resultArray1[i + 1].split("", 10);

        if (item[i][1] != item1[i][1]) {

          if (k == 1) {
            item6.push(item5[i])
          }

          if (k == 3) {
            item6.push(item5[i])    
          }

          if (k == 5) {

            item6.push(item5[i])
          }

          if (k == 7) {

            item6.push(item5[i])
          }

          if (k == 9) {

            item6.push(item5[i])
          }

     }

我尝试通过拆分ID来匹配并给出条件。 现在输出是单维数组。如果它可以是多维的,它将起作用。我是开发新手。任何人都可以帮忙吗?我不能手动这样做。

1 个答案:

答案 0 :(得分:0)

对于没有间隙的排序数据,您可以只查看最后的双零并将此项目用作级别。然后使用帮助程序数组构建一个对象。

var array = [{ ID: "0200000000", Name: "a" }, { ID: "0201000000", Name: "b" }, { ID: "0201010000", Name: "c", }, { ID: "0201010100", Name: "d", }, { ID: "0201010200", Name: "e", }, { ID: "0201010300", Name: "f", }, { ID: "0300000000", Name: "g" }, { ID: "0301000000", Name: "h" }, { ID: "0301010000", Name: "i" }, { ID: "0301010100", Name: "j" }, { ID: "0301010200", Name: "k" }, { ID: "0301010300", Name: "l" }, { ID: "0301010400", Name: "m" }, { ID: "0400000000", Name: "n" }],
    result = [],
    levels = [{ children: result }];

array.forEach(({ ID, Name }) => {
    var path = ID.match(/(..)/g).concat('00'),
        level = path.findIndex(s => s === '00') - 1;

    levels[level].children = levels[level].children || [];
    levels[level].children.push(levels[level + 1] = { Name });
});

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }