首页 > 解决方案 > 迭代对象数组并更新属性

问题描述

我收到具有该结构的对象数组,我试图能够通过它们并连接一个变量,并且链接如下

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",
        },
      ],
    }
 ]

标签: javascript

解决方案


您可以尝试通过对象及其子对象进行映射,然后在前面加上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);


推荐阅读