首页 > 解决方案 > 如何更改树视图中的键?

问题描述

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

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 };
  }
};

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

标签: javascripttypescriptrecursiontreetreeview

解决方案


您可以使用.map()解构和解构来提取所需的属性(id、name、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));


推荐阅读