【问题标题】:How to change a key in tree-view?如何更改树视图中的键?
【发布时间】:2021-10-14 20:57:38
【问题描述】:

我有一个可能的无限树视图数组:

type Tree = {
  id: number;
  name: string;
  email: string;
  children: Tree[];
};

const tree: Tree = [
  {
    id: 1,
    name: 'Truck',
    email: '@mail',
    children: [
      {
        id: 11,
        name: 'Car',
        email: '@mail',
        children: [],
      },
    ],
  },
  {
    id: 2,
    name: 'Bus',
    email: '@mail',
    children: [],
  },
];

我希望对这个数组做 3 件事。

  1. 将属性键“id”更改为“userId”
  2. 将id类型从数字改为字符串
  3. 删除电子邮件属性

所以输出将匹配此类型:

type NewTree = {
  userId: string;
  name: string;
  children: NewTree[];
};

// output of the new tree
const newTree: NewTree = [
  {
    userId: '1',
    name: 'Truck',
    children: [
      {
        userId: '11',
        name: 'Car',
        children: [],
      },
    ],
  },
  {
    userId: '2',
    name: 'Bus'
    children: [],
  },
];

这是我目前拥有的

const restructuredTree = (tree: any[]) => {
  for (const node in tree) {
    const { id: userId, name, children } = tree[node];
    restructuredTree(children);
    tree[node] = { userId, name, children };
  }
};

不确定在哪里执行 return 语句,以及何时返回 "tree[node] = { userId, name, children };"它只改变了一层。

【问题讨论】:

  • 到目前为止,您自己尝试过什么来解决这个问题?
  • 搜索修改单个对象所需的所有内容,使其满足您的要求。然后尝试找到一种遍历嵌套对象的方法。然后结合这两个步骤。
  • 将更新我到目前为止的内容:)

标签: javascript typescript recursion tree treeview


【解决方案1】:

您可以使用.map() 以及解构来提取所需的属性(id、name、children)。对于每个对象,您可以映射到一个新对象,通过递归地重新调用您的函数以执行相同的解构 + 映射逻辑,您可以将 children 键设置为当前 children 数组的重新映射版本。最终,您将到达一个对象,其中 children 键是一个空数组 [],因此不会调用 map 回调,这意味着也不会调用 getNewTree() - 这是您的基本情况/ 将结束递归的终止条件:

const tree = [ { id: 1, name: 'Truck', email: '@mail', children: [ { id: 11, name: 'Car', email: '@mail', children: [], }, ], }, { id: 2, name: 'Bus', email: '@mail', children: [], }, ];

const getNewTree = (tree) => tree.map(({id, name, children}) => ({
  userId: String(id),
  name,
  children: getNewTree(children)
})); 
console.log(getNewTree(tree));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-07
    相关资源
    最近更新 更多