1

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

  • Recursion shouldn't be a headache. It makes these kinds of problems much simpler. – ziggy wiggy Mar 07 '19 at 14:19
  • 1
    Possible duplicate of [JavaScript get value from nested object](https://stackoverflow.com/questions/47503317/javascript-get-value-from-nested-object) – Taki Mar 07 '19 at 14:22
  • What does latest mean for you? Also, all are placed inside of arrays. Can you have parallel objects with same name like [ {name: "root"...}, {name: root} ] – chriss Mar 07 '19 at 14:24
  • https://stackoverflow.com/questions/6491463/accessing-nested-javascript-objects-with-string-key – epascarello Mar 07 '19 at 14:30
  • @epascarello, no, because you need to find the right item of the array. – Nina Scholz Mar 07 '19 at 14:48
  • @NinaScholz it is the same basic concept, it is not a dupe (hence why I did not mark it as such) – epascarello Mar 07 '19 at 14:59

2 Answers2

3

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

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

Tom Finney
  • 2,670
  • 18
  • 12