题目: 将下面的树结构的数据转化为列表的数据。 [ { "name": "北京市", "code": "11", "children": [ { "name": "市辖区", "code": "1101", "children": [ { "name": "东城区", "code": "110101", "children": [] } ] } ] }, { "name": "天津市", "code": "12", "children": [ { "name": "市辖区", "code": "1201", "children": [ { "name": "河北区", "code": "120105", "children": [] } ] } ] }, ]
转化格式:
[ { "name": "北京市", "code": "11", }, { "name": "市辖区", "code": "1101", }, { "name": "东城区", "code": "110101", }, { "name": "天津市", "code": "12", }, { "name": "市辖区", "code": "1201", }, { "name": "河北区", "code": "120105", } ]
测试数据:
var testData = [ { "name": "北京市", "code": "11", "children": [ { "name": "市辖区", "code": "1101", "children": [ { "name": "东城区", "code": "110101", "children": [] } ] } ] }, { "name": "天津市", "code": "12", "children": [ { "name": "市辖区", "code": "1201", "children": [ { "name": "河北区", "code": "120105", "children": [] } ] } ] }, ]
方法:
getListData = (data) => {
let list = [];
data.map((item) => {
// 判断当前item中是否有children
if (item.children) {
// push添加到list ...扩展运算符用于取出参数对象中的所有可遍历属性,拷贝到当前对象之中
// getListData函数,利用了递归,因为我们不知道有多少个children,判断当前数组中对象是否里面有children,有的话继续迭代,直到有没children了,return会返回数组,再用扩展运算符连接起来,再用push添加
list.push(...getListData(item.children));
// delete 排除item.children
delete item.children;
}
list.push(item);
})
return list;
}
getListData(testData)