How can I copy a key of a tree structure to a key with another name or rename it to something else?

Viewed 89

How can I copy a key of a tree structure to a key with another name or rename it to something else?

From this:

[
   {
      "title":"testing",
      "id":1,
      "children":[
         {
            "title":"Preamble",
            "id":2
         }
      ]
   }
]

To this:

[
   {
      "title":"testing",
      "label":"testing",
      "id":1,
      "key":1,
      "children":[
         {
            "title":"Preamble",
            "label":"Preamble",
            "id":2,
            "key":2
         }
      ]
   }
]

in this one the label is a copy of title and the the key a copy of id.

or this:

[
   {
      "label":"testing",
      "key":1,
      "children":[
         {
            "label":"Preamble",
            "key":2
         }
      ]
   }
]

in this one the title is renamed to label and the id to key.

The tree structure can have a lot nodes / children.

1 Answers

You could take a mapping function which maps the children as well.

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

Related