javascript - 如何更改树视图中的键?
问题描述
我有一个可能的无限树视图数组:
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 件事。
- 将属性键“id”更改为“userId”
- 将 id 类型从数字更改为字符串
- 删除电子邮件属性
所以输出将匹配这种类型:
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 };” 它只改变了一层。
解决方案
您可以使用.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));
推荐阅读
- css - 在 Firefox 中渲染特殊字符
- python - 两个时间戳之间的差异四舍五入到数小时并将列添加到数据框
- curl - 卷曲创建一个大的帖子请求
- swift - 如何在 swift 4 中获取 CATextLayer 的“字符串”属性值?
- ios - 如何以编程方式将视图添加到合金中的滚动视图
- ios - 更改滑块上拇指图像的位置
- excel - VBS - 将制表符分隔的 CSV 文件转换为 XLSX
- android - 如何将按钮插入导航工具栏
- apache-kafka - 在 Kafka 中,无法使用 kafka-consumer-groups.sh 创建新的消费者
- javascript - JavaScript split() 使用一个公共字符,然后 join() 使用不同的字符