We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
先说结果代码:
const flatTree = (arr) => { return arr.reduce((item, next) => { return next.children ? item.concat(flat(next.children), next) : item.concat(next) }, []) }
测试数据:
const city = [ { value: '11', children: [ { value: '11', children: [ { value: '1100' } ] } ] }, { value: '12', children: [ { value: '120', children: [ { value: '1200' } ] } ] }, { value: '22', children: [ {value: '220'}, {value: '221', children: [{value: '2210'}]} ] } ]
项目需要,我一般这样去平铺树结构的:
let result = []; const flat = (arr) => { arr.forEach(item => { result.push(item); item.children && flat(item.children); }) } flat(目标树数据); // 然后得到平铺后的result
很low有没有? 但是抱歉,我一直都这样玩的。。。
直到上周看到前端群里有人只用了大概一两行代码就实现我这么多行代码的功能,我当时就震惊了。虽然当时比较闲,但是处于划水状态,我也认真看了,以为我理解了,直到今天下午用到时,我才发现我根本不会!!!
我下午想了两小时,一直错以为内部用map,就这样陷入死境,根本想不通。我下午这样想的:
map
const flat = (arr) => { return arr.map(item => { return item.children ? flat(item.children).concat(item) : item; }) }
打印测试才发现,一点变化都没有!!!我一直都在纠结怎么让flat(item.children)执行的结果数据平铺到父级数组中,我到处加...,不是报错就是没用。
flat(item.children)
...
就在刚刚,跟朋友聊到,他说flat可不可以,我当时就否了,毕竟内部是树结构对象,flat在内部元素是基本类型才行,不过,我还是去MDN上看了下,结果,卧槽,多亏了朋友阳阳,我看到有个 reduce+concat 模拟实现flat功能的方法,卧槽,我的回忆也立马出现,就是 reduce+concat !!!
flat
然后我开始尝试着去写,发现对reduce还是不熟,说到底写不出来就是不理解,不熟练!!!
reduce
丢人!!!
The text was updated successfully, but these errors were encountered:
No branches or pull requests
先说结果代码:
测试数据:
项目需要,我一般这样去平铺树结构的:
很low有没有?
但是抱歉,我一直都这样玩的。。。
直到上周看到前端群里有人只用了大概一两行代码就实现我这么多行代码的功能,我当时就震惊了。虽然当时比较闲,但是处于划水状态,我也认真看了,以为我理解了,直到今天下午用到时,我才发现我根本不会!!!
我下午想了两小时,一直错以为内部用
map
,就这样陷入死境,根本想不通。我下午这样想的:打印测试才发现,一点变化都没有!!!我一直都在纠结怎么让
flat(item.children)
执行的结果数据平铺到父级数组中,我到处加...
,不是报错就是没用。就在刚刚,跟朋友聊到,他说flat可不可以,我当时就否了,毕竟内部是树结构对象,flat在内部元素是基本类型才行,不过,我还是去MDN上看了下,结果,卧槽,多亏了朋友阳阳,我看到有个 reduce+concat 模拟实现
flat
功能的方法,卧槽,我的回忆也立马出现,就是 reduce+concat !!!然后我开始尝试着去写,发现对
reduce
还是不熟,说到底写不出来就是不理解,不熟练!!!丢人!!!
The text was updated successfully, but these errors were encountered: