首页 > 解决方案 > 如何将树结构的键复制到具有其他名称的键或将其重命名为其他名称?

问题描述

如何将树结构的键复制到具有其他名称的键或将其重命名为其他名称?

由此:

[
   {
      "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 被重命名为键。

树结构可以有很多节点/子节点。

标签: javascripttypescript

解决方案


您也可以使用映射子项的映射函数。

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


推荐阅读