平常在使用学习js,有嵌套层级的数组,这种情况下就需要我们自行封装方法去组装数据结构,具体的代码如下:
input: [
{
id: 1,
text: "text1",
children: [
{ id: 2, text: "text2", parentId: 1, children: [{ id: 4, text: "text4", parentId: 2 }] },
{ id: 3, text: "text3", parentId: 1 },
],
},
];
// 上面数据转换成下面数据
input: [
{ id: 4, text: "text4", parentId: 2 },
{ id: 2, text: "text2", parentId: 1 },
{ id: 3, text: "text3", parentId: 1 },
{ id: 1, text: "text1" },
];
js封装,代码如下:
解释:一开始我们先传入一个树形结构,对传入的tree数组进行遍历,遍历中用if判断每个数组中是否有children,没有children直接输出,否则进行if中的迭代,在返回给arr。详情在代码中。
const walk = (tree, arr = []) => {
// 遍历tree数组
// map() 对数组中的每一项运行给定函数,返回每次函数调用的结果组成的数组,返回就是数组,不考虑true或者false;
tree.map((item) => {
// 判断当前itme中是否有children
if (item.children) {
// push添加到arr ...扩展运算符用于取出参数对象中的所有可遍历属性,拷贝到当前对象之中
// walk函数,利用了迭代,因为我们不知道有多少个children,判断当前数组中对象是否里面有children,有的话继续迭代,直到有没children了,return会返回数组,再用扩展运算符连接起来,再用push添加
arr.push(...walk(item.children));
// delete 排除item.children
delete item.children;
}
arr.push(item);
});
// 返回结果
return arr;
};
let input = [
{
id: 1,
text: "text1",
children: [
{ id: 2, text: "text2", parentId: 1, children: [{ id: 4, text: "text4", parentId: 2 }] },
{ id: 3, text: "text3", parentId: 1 },
],
},
];
console.log(walk(input));
有问题可以私信我或者下方留言