-1

Lets say have an Array of Objects that looks like this:

    let example = [
      {
        children: [{
          data: { id: 2, group: 1001, name: "Audi" },
        }],
        data: { id: 1, group: 1000, name: "Cars" }
      },
      {
        children: [{
          data: { id: 4, group: 1003, name: "Airbus A320" },
        }],
        data: { id: 3, group: 1002, name: "Planes" }
      },
      {
        children: [{
          data: { id: 6, group: 1005, name: "Departed" }
        }],
        data: { id: 5, group: 1006, name: "movies" }
      }
    ]

In my application the User selects a Tablerow and i get the selected Row Information aka the 'data' object e.g.

{ id: 2, group: 1001, name: "Audi" }

Now i want to find that selected data object based on the Id in my Array using lodash or javascript/typescript.

How would i achive that? The children Array causes me problems.

EDIT: The Child of a Child should also be found.

{
        children: [{
          children: [{
             data: {id : 7, group 1001, name: "A8"},
             children: [{...}]
          }],
          data: { id: 2, group: 1001, name: "Audi" },
        }],
        data: { id: 1, group: 1000, name: "Cars" }
      }
5
  • Are you asking for an answer in TypeScript or JavaScript? Commented Oct 16, 2018 at 15:17
  • @PatrickRoberts In TypeScript or JavaScript doesnt matter at the moment. Commented Oct 16, 2018 at 15:19
  • Do you want to find the data object inside the array for the selected data object's id or do you want to find the data inside the children array for the select data object's id ? Commented Oct 16, 2018 at 15:25
  • I want to find both Commented Oct 16, 2018 at 15:31
  • Other possible duplicate: stackoverflow.com/questions/50381450/… Commented Oct 16, 2018 at 15:50

1 Answer 1

1

/** find by id data using recursion */
function findById(data, id) {
  for (const datum of data) {
    if (datum.data.id == id) return datum
    if (datum.children) {
      let result = findById(datum.children, id)
      if (result) return result
    }
  }
}


let example = [{
    children: [{
      data: {
        id: 2,
        group: 1001,
        name: "Audi"
      },
    }],
    data: {
      id: 1,
      group: 1000,
      name: "Cars"
    }
  },
  {
    children: [{
      data: {
        id: 4,
        group: 1003,
        name: "Airbus A320"
      },
    }],
    data: {
      id: 3,
      group: 1002,
      name: "Planes"
    }
  },
  {
    children: [{
      data: {
        id: 6,
        group: 1005,
        name: "Departed"
      }
    }],
    data: {
      id: 5,
      group: 1006,
      name: "movies"
    }
  }
]



console.log(findById(example, 2))

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.