前端JS面试题:复杂对象转为数组矩阵

73 阅读1分钟

问题描述

根据下面数据模型过滤成指定格式数组,可以使用lodash

相关代码

let data = {

  type: 1,
  childNode: {
    type: 4,
    childNode: null,
    conditionNodes: [
      {
        type: 3,
        childNode: {
          type: 1,
          childNode: null
        }
      },
      {
        type: 3,
        childNode: {
          type: 4,
          childNode: null,
          conditionNodes: [
            {
              type: 3,
              childNode: {
                type: 1,
                childNode: null
              }
            },
            {
              type: 3,
              childNode: {
                type: 1,
                childNode: null
              }
            }
          ]
        }
      },
      {
        type: 3,
        childNode: {
          type: 1,
          childNode: null
        }
      }
    ]
  }
}

说明 只有type4 下可以有数组,其他全是单项

你期待的结果是什么?实际看到的错误信息又是什么?

期待结果

[[1],[4],[3,3,3],[0,4,0],[1,[3,3],1],[0,[1,1],0]]

1和3全为对象,4为数组,4下边只能跟3,如果出现4同级为3,同级的3用0占位,放到下一级,也就是说4永远和4或0在一行,1和3在一行

示例模型

就像下边的矩阵,横线为上面数组,下边示例紧接上面可以改变示例继续无限层级追加

                1

                4

    3            3            3

    0            4            0

    1        3       3        1

    0        1       1        0

    0         4       4        0

    0       3   3    3   3     0        

    0       1   1    1   1     0

欢迎回复解答