javascript - 迭代对象数组并更新属性
问题描述
我收到具有该结构的对象数组,我试图能够通过它们并连接一个变量,并且链接如下
link: `${id}/users`
link: `${id}/add-user`
...
id= school1;
dashboardMenu = [
{
title: "Dashboard",
icon: "home-outline",
link: "/",
home: true,
children: undefined,
},
{
title: "Users",
icon: "person-outline",
link: "/users",
data: "read:users",
children: [
{
title: "Users",
link: "/users",
data: "read:users",
},
{
title: "Create User",
link: "/add-user",
data: "create:users",
},
],
}
]
解决方案
您可以尝试通过对象及其子对象进行映射,然后在前面加上id
,例如:
let id = "school1";
let dashboardMenu = [
{
title: "Dashboard",
icon: "home-outline",
link: "/",
home: true,
children: undefined,
},
{
title: "Users",
icon: "person-outline",
link: "/users",
data: "read:users",
children: [
{
title: "Users",
link: "/users",
data: "read:users",
},
{
title: "Create User",
link: "/add-user",
data: "create:users",
},
],
},
];
let result = dashboardMenu.map((o) => {
o.link = id + o.link;
if (o.children) {
o.children.forEach((child) => (child.link = id + child.link));
}
return o;
});
console.log(result);
递归地,您可以执行以下操作:
let dashboardMenu = [{
title: "Dashboard",
icon: "home-outline",
link: "/",
home: true,
children: undefined,
},
{
title: "Users",
icon: "person-outline",
link: "/users",
data: "read:users",
children: [{
title: "Users",
link: "/users",
data: "read:users",
},
{
title: "Create User",
link: "/add-user",
data: "create:users",
},
],
},
];
setNestedLink = (o, k, id) => {
if (o[k]) {
o[k] = id + o[k];
if (o.children) {
o.children.forEach((child) => setNestedLink(child, k, id));
}
}
return o;
};
let result = dashboardMenu.map((o) => setNestedLink(o, "link", "school1"));
console.log(result);
推荐阅读
- mysql - 自加入 - 当我尝试进行自加入时,我的查询显示匹配和不匹配的值
- python - 带有 Tensorflow 的神经网络不会更新权重/偏差
- django - 使用 python+django+gunicorn + worker 无法启动 Gcloud 应用程序部署失败
- html - 如何自动生成唯一的 CSS 选择器
- jquery - 显示每个中继器项目的值
- python - 从python中的迭代对象创建一个带有一组树的迭代对象
- mysql - 每个组的 MySQL top-N 排名,基于最新组的行
- html - 将多种背景颜色设置为 H1
- google-sheets - 用于日期检测的 Google 表格公式
- r - 如何在素食包的布雷 nmds 分析中添加椭圆