2

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.

wilbi
  • 225
  • 2
  • 14
  • Does this answer your question? [JavaScript: Object Rename Key](https://stackoverflow.com/questions/4647817/javascript-object-rename-key) – Heretic Monkey Jan 13 '21 at 13:12
  • Or [Rename Object Keys from Snake Case to Camel Case Recursively Without Using Lodash](https://stackoverflow.com/q/58257467/215552) – Heretic Monkey Jan 13 '21 at 13:21
  • @HereticMonkey it does the job for a single key in an object, but I need it for a tree structure which means somehow we have to traverse through it's nodes and do the changes. Thanks for your comment. – wilbi Jan 13 '21 at 13:37
  • And the second link? Also, you could just call the first one recursively... – Heretic Monkey Jan 13 '21 at 13:38
  • @HereticMonkey the second link is more promising, I just need to see how it can work for my case. – wilbi Jan 13 '21 at 13:39

1 Answers1

1

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; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392