猿问

js 多层嵌套的数组,取出最后一层的数据?

需要获取到isCheck = true 的所有id的集合


list: [{

  id: '1',

  isCheck: false,

  children: [{

    id: '1-1',

    isCheck: false,

    children: null

  }, {

    id: '1-2',

    isCheck: true,

    children: null

  }]

}, {

  id: '2',

  isCheck: false,

  children: [{

    id: '2-1',

    isCheck: true,

    children: null

  }]

}, {

  id: '3',

  isCheck: true,

  children: null

}]

想到用递归算法,把数组扁平化降级,可是获取到的数据不对,希望获取到数据为


['1-2', '2-1', '3']

  steamroller: function (arr) {

    let newArr = []

    let flat = function (item) {

      for (var i = 0; i < item.length; i++) {

        if (Array.isArray(item[i].children)) {

          flat(item[i])

        } else {

          newArr.push(item[i])

        }

      }

    }

    flat(arr)

    return newArr

  }

求助求助!


泛舟湖上清波郎朗
浏览 3646回答 3
3回答

拉风的咖菲猫

const result = [],&nbsp; getId = arr => {&nbsp; &nbsp; arr.forEach(v => {&nbsp; &nbsp; &nbsp; &nbsp; v.isCheck && result.push(v.id);&nbsp; &nbsp; &nbsp; &nbsp; if (v.children instanceof Array) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; getId(v.children)&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; });}getId(list);console.log(result) //["1-2", "2-1", "3"]递归一下

缥缈止盈

你是想要获取到所有的 children 下面的 id?function funEach(data){&nbsp; &nbsp; var arr = new Array();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //&nbsp; &nbsp; 准备空数组存放&nbsp; &nbsp; /*&nbsp; &nbsp; 第一层是索引数组 */&nbsp; &nbsp; for(var i = 0;i < data.length;i++){&nbsp; &nbsp; &nbsp; &nbsp; /*&nbsp; &nbsp;该判断通过,说明下面具有值&nbsp; &nbsp; &nbsp;*/&nbsp; &nbsp; &nbsp; &nbsp;if(data[i]['children'][0] != undefined){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;var l = data[i]['children'][0];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //&nbsp; &nbsp; 准备个临时变量&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;for(var iOne = 0;iOne < l.length;i++){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;arr[] = l['id'];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; }&nbsp; &nbsp; return arr;}嗯,按我逻辑来想的话应该是没问题的。
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答