js 用迭代器模式优雅的处理递归问题
什么是迭代器
循环数组或对象内每一项值,在 js 里原生已经提供了一个迭代器。
var arr = [1, 2, 3]
arr.forEach(function (item) {
console.log(item)
})实现一个迭代器
var iterator = function (arr, cb) {
for (let i = 0; i < arr.length; i++) {
cb.call(arr[i], arr[i], i)
}
}
var cb = function (item, index) {
console.log('item is %o', item)
console.log('index is %o', index)
}
var arr = [1, 2, 3]
iterator(arr, cb)
/*
打印:
item is 1
index is 0
item is 2
index is 1
item is 3
index is 2
*/实际应用
需求:
- Antd 的嵌套表格组件的数据源有要求,如果没有子元素,children 属性应该设置为 null 或者删除 children 属性,实际开发中后端返回的接口却是没有子元素时,children 属性设置为一个空数组;
- 后端返回的字段名 categoryId 字段名更改为 value,name 字段名更改为 label。
数据结构修改前后示例。
var categoryList = [
{
categoryId: 1,
name: '1级',
children: [
{
categoryId: 11,
name: '11级',
children: [],
},
],
},
{
categoryId: 2,
name: '2级',
children: []
}
]
// 处理之后数据结构如下
var categoryList = [
{
value: 1,
label: '1级',
children: [
{
value: 11,
label: '11级',
},
],
},
{
value: 2,
label: '2级',
}
]
使用迭代器模式优雅的处理递归类问题。
// 数据源
var categoryList = [
{
categoryId: 1,
name: '1级',
children: [
{
categoryId: 11,
name: '11级',
children: [],
},
],
},
{
categoryId: 2,
name: '2级',
children: []
}
]
// 迭代器
var iterator = function (arr, cb) {
for (let i = 0; i < arr.length; i++) {
cb.call(arr[i], arr[i])
}
}
// 处理每一项
var changeItem = function (item) {
// 更改字段名称
item.value = item.categoryId
item.label = item.name
delete item.categoryId
delete item.name
// 当 children 为空数组时,删除 children 属性
if (item.children == false) {
delete item.children
} else {
iterator(item.children, changeItem)
}
}
// 调用迭代器
iterator(categoryList, changeItem)
console.log(JSON.stringify(categoryList, null, 4))
/*
打印:
[
{
"children": [
{
"value": 11,
"label": "11级"
}
],
"value": 1,
"label": "1级"
},
{
"value": 2,
"label": "2级"
}
]
*/总结
凡是需要用到递归的函数参考迭代器模式,能写出更优雅,可读性更高的代码。
本文内容仅供个人学习、研究或参考使用,不构成任何形式的决策建议、专业指导或法律依据。未经授权,禁止任何单位或个人以商业售卖、虚假宣传、侵权传播等非学习研究目的使用本文内容。如需分享或转载,请保留原文来源信息,不得篡改、删减内容或侵犯相关权益。感谢您的理解与支持!