如何将含箭头函数和扩展运算符的JS层级查询代码改为普通函数写法
扩展运算符替换实现方案
替换思路
共两处用到扩展运算符,可分别用原生旧语法替代:
- 数组场景扩展:原代码
[e.id, ...children(e.id, data)]的作用是将children返回的数组元素逐个合并到当前数组,直接用数组原生concat方法即可实现完全等价的效果 - 对象场景扩展:原代码
{ ...data.find(...), children: xxx }的作用是复制查询到的对象所有属性后追加children属性,可通过遍历复制对象属性的方式实现,避免直接修改原数组内的原始数据
完整可运行代码
data = [{"id":63,"parent":59,"currency":1},{"id":64,"parent":59,"currency":1},{"id":1,"parent":null,"currency":1},{"id":2,"parent":1,"currency":4},{"id":4,"parent":3,"currency":4},{"id":3,"parent":2,"currency":2},{"id":5,"parent":1,"currency":5},{"id":6,"parent":1,"currency":6},{"id":7,"parent":3,"currency":2},{"id":8,"parent":1,"currency":1},{"id":57,"parent":56,"currency":1},{"id":58,"parent":1,"currency":1},{"id":59,"parent":1,"currency":1},{"id":30,"parent":1,"currency":1},{"id":31,"parent":1,"currency":1},{"id":32,"parent":1,"currency":1},{"id":33,"parent":1,"currency":1},{"id":34,"parent":1,"currency":1},{"id":35,"parent":1,"currency":1},{"id":36,"parent":1,"currency":18},{"id":37,"parent":1,"currency":1},{"id":39,"parent":1,"currency":1},{"id":41,"parent":6,"currency":6},{"id":42,"parent":1,"currency":1},{"id":43,"parent":42,"currency":1},{"id":48,"parent":47,"currency":2},{"id":47,"parent":37,"currency":2},{"id":49,"parent":48,"currency":2},{"id":52,"parent":1,"currency":16},{"id":9,"parent":1,"currency":9},{"id":54,"parent":1,"currency":4},{"id":55,"parent":1,"currency":1},{"id":56,"parent":1,"currency":1},{"id":19,"parent":1,"currency":12},{"id":21,"parent":1,"currency":1},{"id":12,"parent":1,"currency":1},{"id":13,"parent":1,"currency":1},{"id":15,"parent":1,"currency":1},{"id":16,"parent":1,"currency":1},{"id":10,"parent":1,"currency":8},{"id":11,"parent":1,"currency":4},{"id":66,"parent":1,"currency":1},{"id":69,"parent":68,"currency":1},{"id":65,"parent":1,"currency":1},{"id":68,"parent":1,"currency":1},{"id":70,"parent":1,"currency":11}] function children(id, data) { return data.filter(function(e){return e.parent === id}).flatMap(function(e){ // concat替代数组扩展运算符 return [e.id].concat(children(e.id, data)) }) } function find(id, data) { var originItem = data.find(function(e){return e.id === id}); // 遍历复制属性替代对象扩展运算符 var result = {}; for (var key in originItem) { if (originItem.hasOwnProperty(key)) { result[key] = originItem[key]; } } result.children = children(id, data).sort(function(a, b) { return a === b ? 0 : a > b ? 1 : -1}); return result; } console.log(find(1, data));
如果运行环境不支持flatMap方法,可将children函数改写为循环实现:
function children(id, data) { var filtered = data.filter(function(e){return e.parent === id}); var result = []; for (var i = 0; i < filtered.length; i++) { var e = filtered[i]; result.push(e.id); result = result.concat(children(e.id, data)); } return result; }
内容的提问来源于stack exchange,提问作者NooB Gamer
相关产品推荐
相关产品推荐

