【问题标题】:How can I copy a key of a tree structure to a key with another name or rename it to something else?如何将树结构的键复制到具有其他名称的键或将其重命名为其他名称?
【发布时间】:2021-01-13 21:40:00
【问题描述】:

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

来自:

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

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

【问题讨论】:

标签: javascript typescript


【解决方案1】:

您可以采用映射函数来映射孩子。

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

【讨论】:

    猜你喜欢
    • 2014-11-26
    • 1970-01-01
    • 2022-11-10
    • 2016-10-19
    • 2014-01-22
    • 2021-08-27
    • 2022-08-23
    • 2017-09-17
    • 1970-01-01
    相关资源
    最近更新 更多