0

I have a tree structure going like this:

    public folders: any[] = [

    {name : 'Inbox', id : 1, folders : []},
    {name : 'Draft', id : 2, folders : []},
    {name : 'Spam', id : 3, folders : []},
    {name : 'Trash', id : 4, folders : [
      {name : 'Trash lvl 1', id : 5, folders : [
        {name : 'Trash lvl 2', id : 6, folders: []}
      ]}
    ]},
  ];

After that I'll get some list of indexes, going like this:

var ids = [3, 0, 0];

What would be the most effective JavaScript/TypeScript way of selecting following object:

 {name : 'Trash lvl 2', id : 6, folders: []}

So I need something like this, only dynamically:

 console.log(this.folders[3]['folders'][0]['folders'][0]);
Wrapper
  • 794
  • 10
  • 25

2 Answers2

2

You could reduce the index array by taking the folder property with the given index.

As start value take an object with a folder property.

const
    folders = [{ name: 'Inbox',  id: 1, folders: [] }, { name: 'Draft', id: 2, folders: [] }, { name: 'Spam', id: 3, folders: [] }, { name: 'Trash', id: 4, folders: [{ name: 'Trash lvl 1', id: 5, folders: [{ name: 'Trash lvl 2', id: 6, folders: [] }] }] }],
    indices = [3, 0, 0],
    target = indices.reduce(
        ({ folders }, index) => folders[index],
        { folders }
    );

console.log(target);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
1

By creating a higher level object of the form

{ folders : folders }

you can then pass that as the initial value to a reduce on ids, selecting at each iteration the folders value indexed by the id value:

const folders = [
  {name : 'Inbox', id : 1, folders : []},
  {name : 'Draft', id : 2, folders : []},
  {name : 'Spam', id : 3, folders : []},
  {name : 'Trash', id : 4, folders : [
    {name : 'Trash lvl 1', id : 5, folders : [
      {name : 'Trash lvl 2', id : 6, folders: []}
    ]}
  ]},
];

const ids = [3, 0, 0];

const result = ids.reduce((c, id) => c.folders[id], { folders });

console.log(result);
Nick
  • 138,499
  • 22
  • 57
  • 95