js 数组对象有多层数据,但只保留两层,该如何解决?
模拟数据代码贴上:
let nav = [{name: "用户中心",
code: "userManage",
url: "",
component: "",
children: [{
name: "角色管理",
code: "userRole",
url: "",
component: "",
children: [{
name: "新建",
code: "create"
}]
},
{
name: "用户管理",
code: "userList",
url: "",
component: "",
children: [{
name: "编辑",
code: "redact"
}]
}
]
},
{
name: "系统管理",
code: "systemManage",
url: "",
component: "",
children: [{
name: "应用管理",
code: "system",
url: "",
component: "",
children: [{
name: "新建",
code: "create"
}]
}]
}
]
最后要得到的结果:
[{name: "用户中心",
code: "userManage",
url: "",
component: "",
children: [{
name: "角色管理",
code: "userRole",
url: "",
component: ""
},
{
name: "用户管理",
code: "userList",
url: "",
component: ""
}
]
},
{
name: "系统管理",
code: "systemManage",
url: "",
component: "",
children: [{
name: "应用管理",
code: "system",
url: "",
component: ""
}]
}
]
回答
因为你这个只有children子属性中存在多层,所以在复制对象时,只处理首层的children子属性,其他层次的都不再处理。
let nav = [ {
name: "用户中心",
code: "userManage",
url: "",
component: "",
children: [
{
name: "角色管理",
code: "userRole",
url: "",
component: "",
children: [
{
name: "新建",
code: "create",
},
],
},
{
name: "用户管理",
code: "userList",
url: "",
component: "",
children: [
{
name: "编辑",
code: "redact",
},
],
},
],
},
{
name: "系统管理",
code: "systemManage",
url: "",
component: "",
children: [
{
name: "应用管理",
code: "system",
url: "",
component: "",
children: [
{
name: "新建",
code: "create",
},
],
},
],
},
];
const _ = require('lodash')
function filter(arr) {
let result = _.cloneDeepWith(arr);
for (let firstLayer of result) {
if (firstLayer.children) {
for (let secondLayer of firstLayer.children) {
delete secondLayer.children;
}
}
}
return result;
}
let result = filter(nav);
console.log("result",result[0].children[0]);
console.log("原数据",nav[0].children[0]);
const fn = (data, limited = 1) => data.map(({ children, ...rest }) =>
({
...rest,
...(limited === 2 ? {} : { children: fn(children, limited + 1) })
})
);
const result = nav.map(item => { const children = item.children.map(every => {
return {
name: every.name,
code: every.code,
url: every.url,
component: every.component,
};
})
return {
...item,
children: children
};
})
以上是 js 数组对象有多层数据,但只保留两层,该如何解决? 的全部内容, 来源链接: utcz.com/a/28833.html