javascript - 如何将树结构的键复制到具有其他名称的键或将其重命名为其他名称?
问题描述
如何将树结构的键复制到具有其他名称的键或将其重命名为其他名称?
由此:
[
{
"title":"testing",
"id":1,
"children":[
{
"title":"Preamble",
"id":2
}
]
}
]
对此:
[
{
"title":"testing",
"label":"testing",
"id":1,
"key":1,
"children":[
{
"title":"Preamble",
"label":"Preamble",
"id":2,
"key":2
}
]
}
]
在这个中,标签是标题的副本,键是 id 的副本。
或这个:
[
{
"label":"testing",
"key":1,
"children":[
{
"label":"Preamble",
"key":2
}
]
}
]
在这一个中,标题被重命名为标签,ID 被重命名为键。
树结构可以有很多节点/子节点。
解决方案
您也可以使用映射子项的映射函数。
const
newStructure = ({ title, label = title, id, key = id, children }) => ({
title, label, id, key,
...(children && { children: children.map(newStructure) })
}),
data = [{ title: "testing", id: 1, children: [{ title: "Preamble", id: 2 }] }],
result = data.map(newStructure);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
推荐阅读
- assembly - MIX 中 STA (0:1) 的行为是什么?
- javascript - validateForm()有bug时如何避免onsubmit="return validateForm()"提交表单?
- django - 如何在我的 Django 项目中使用需要 conda 环境的第三方存储库
- java - 我不明白为什么这不起作用线程“main”java.util.InputMismatchException中的异常
- javascript - 来自php脚本/ unixtime的Highcharts格式json数据
- javascript - 表格行不能作为 div 组件的子项出现
- ios - collectionView Header 中的搜索栏实现
- python - Plotly:在美国的 Choropleth 上写下数字
- android - android - 在 Android 9.1 中未收到 Firebase 通知
- c# - JSON序列化函数返回空字符串