-1

This is my variable tree:

enter image description here

I want to find the element by it path. (in the case `Documents it is 0)

Like this myFolder gives me the correct output:

var myFolder = tree.childs[0]

But I do not have the key, I have only the path. I tried:

var myFolder = tree.map(Folder => Folder.path).indexOf('Documents/');

But I get an error message (implicity has an 'any' type)

peace_love
  • 6,229
  • 11
  • 69
  • 157
  • 1
    Does this answer your question? [Find object by id in an array of JavaScript objects](https://stackoverflow.com/questions/7364150/find-object-by-id-in-an-array-of-javascript-objects) – Ivar Jul 15 '22 at 15:21
  • @Ivar Thank you. I tried this `var obj = _.find(tree, function (obj) { return obj.path == 'Documents/' })` but still error – peace_love Jul 15 '22 at 15:24
  • @Ivar I also tried `var item = tree.find(item => item.path === 'Documents/')` still error – peace_love Jul 15 '22 at 15:26
  • can you provide some example data of your tree in code? (not the screenshot) – Dean Jul 15 '22 at 15:27
  • 1
    See [Typescript: TS7006: Parameter 'xxx' implicitly has an 'any' type](https://stackoverflow.com/questions/43064221/typescript-ts7006-parameter-xxx-implicitly-has-an-any-type) – Ivar Jul 15 '22 at 15:29
  • It works now: var item = tree.childs.find(item => item.path === 'Documents/') – peace_love Jul 15 '22 at 15:29
  • does this mean your tree is never more than one level deep? – Dean Jul 15 '22 at 15:29
  • Please edit your question to include textual input, rather than a screenshot. – user229044 Jul 15 '22 at 15:34

1 Answers1

1
const mainFolder = {
    childs: [
        { path: 'ExamplePathNameOne' },
        { path: 'ExamplePathNameTwo' },
        { path: 'ExamplePathNameThree' },
    ]
}

const folder = mainFolder.childs.find(c => c.path === 'ExamplePathNameOne');

But to fix your error message, either set "noImplicitAny": false in your tsconfig.json file or define an interface for the objects you are using, f.e. MainFolder and Folder.

interface MainFolder {
    childs: Folder[];
}

interface Folder {
    path: string;
}

const mainFolder: MainFolder = {
    childs: [
        { path: 'ExamplePathNameOne' },
        { path: 'ExamplePathNameTwo' },
        { path: 'ExamplePathNameThree' },
    ]
}

const folder = mainFolder.childs.find(c => c.path === 'ExamplePathNameOne');
Optimal
  • 407
  • 3
  • 9