JavaScript find recursively by path

I have the following data structure:

[
  {
    name: 'root',
    children: [
      {
        name: 'page',
        children: [
          // and so on
        ]
      }
    ]
  }
]

I need a function to get the latest object given by a path. E.g. getCurrentTree('root.page')should return

      {
        name: 'page',
        children: [
          // and so on
        ]
      }

I hope you understand what I mean! I know I should do it recursively, but recursion is always a headache for me. Also I am not sure if should do this with find or filter? or even reduce? Does anybody have a smart idea?

Cheers

Upvotes: 1

Views: 1205

Answers (2)

Tom Finney
Tom Finney

Reputation: 2918

Something like?

let mainList = [
  {
    name: 'root',
    children: [
      {
        name: 'page',
        children: [

        ]
      }
    ]
  }
]

function getCurrentTree(path) {
  const paths = path.split('.')
  return traverse(mainList, paths, 0) 
}

function traverse(list, paths, level) {
  const node = list.find(obj => obj.name === paths[level])

  if (level === paths.length - 1) {
    return node
  } else {
    return traverse(node.children, paths, level + 1)
  }
}

getCurrentTree("root.page")
// => {name: "page", children: Array(0)}

Upvotes: 1

Nina Scholz
Nina Scholz

Reputation: 386570

You could check the name and iterate for the children or return the object.

function getCurrentTree(array, names) {
    var [name, path] = names.split('.', 2),
        result;

    array.some(o => {
        if (o.name === name) {
            return result = path ? getCurrentTree(o.children, path) : o;
        }
    });
    return result
}

var data = [{ name: 'root', children: [{ name: 'page', children: [] }] }];

console.log(getCurrentTree(data, 'root.page'));

Upvotes: 3

Related Questions