webber
webber

Reputation: 765

How to change a key in tree-view?

I have a possible infinite tree-view array:

type Tree = {
  id: number;
  name: string;
  email: string;
  children: Tree[];
};

const tree: Tree = [
  {
    id: 1,
    name: 'Truck',
    email: '@mail',
    children: [
      {
        id: 11,
        name: 'Car',
        email: '@mail',
        children: [],
      },
    ],
  },
  {
    id: 2,
    name: 'Bus',
    email: '@mail',
    children: [],
  },
];

There are 3 things I wish to do to this array.

  1. change the property key 'id' to 'userId'
  2. change the id type from number to string
  3. remove the email property

so the output will match this type:

type NewTree = {
  userId: string;
  name: string;
  children: NewTree[];
};

// output of the new tree
const newTree: NewTree = [
  {
    userId: '1',
    name: 'Truck',
    children: [
      {
        userId: '11',
        name: 'Car',
        children: [],
      },
    ],
  },
  {
    userId: '2',
    name: 'Bus'
    children: [],
  },
];

This is what I currently have

const restructuredTree = (tree: any[]) => {
  for (const node in tree) {
    const { id: userId, name, children } = tree[node];
    restructuredTree(children);
    tree[node] = { userId, name, children };
  }
};

Not sure where to do a return statement, and when I return "tree[node] = { userId, name, children };" it's only changing one level deep.

Upvotes: 0

Views: 764

Answers (1)

Nick Parsons
Nick Parsons

Reputation: 50749

You can use .map() as well as destructuring to pull out the desired properties (id, name, children). For each object, you can map to a new object, where you set the children key to be the re-mapped version of the current children array by recursively re-calling your function to perform the same destructuring + mapping logic. Eventually, you'll reach an object where the children key is an empty array [], and so the map callback won't be called which means that getNewTree() won't be called either - this acts as your base-case / termination condition that will end the recursion:

const tree = [ { id: 1, name: 'Truck', email: '@mail', children: [ { id: 11, name: 'Car', email: '@mail', children: [], }, ], }, { id: 2, name: 'Bus', email: '@mail', children: [], }, ];

const getNewTree = (tree) => tree.map(({id, name, children}) => ({
  userId: String(id),
  name,
  children: getNewTree(children)
})); 
console.log(getNewTree(tree));

Upvotes: 1

Related Questions