Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

152
Views
get id by value in hierarcial data with js

I have hierarcial data as tree array:

var myData = [
    {
      id: 0,
      title:"Item 1"
    }, {
      id: 1,
      title:"Item 2",
      subs: [
        {
          id: 10,
          title:"Item 2-1"
        }, {
          id: 11,
          title:"Item 2-2"
        }, {
          id: 12,
          title:"Item 2-3"
        }
      ]
    }, {
      id: 2,
      title:"Item 3"
    },
    // more data here
];

I need to get id by title in this array. I try to use this function:

console.log(myData.findIndex(item=>item.title==="Item 3"))

But it works bad for "Item 2-2". How should I solve this problem?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

I made this simple findId method in order to find the title and returns the id or undefined as result made for your data array structure.

This will work fine, assuming each title is unique in the array.
Otherwise only the first will be found.

Take a look at the following

var myData = [{
    id: 0,
    title: "Item 1"
  }, {
    id: 1,
    title: "Item 2",
    subs: [{
      id: 10,
      title: "Item 2-1"
    }, {
      id: 11,
      title: "Item 2-2"
    }, {
      id: 12,
      title: "Item 2-3"
    }]
  }, {
    id: 2,
    title: "Item 3"
  },
  // more data here
];

function findId(title) {
  // Item with the equal title or with a children with an equal title
  const item = myData.filter(d => (d.title === title || d?.subs?.filter(s => s.title === title).length > 0))[0];

  if (item) {
    // Check if is the main element or is one of the subs (with ternary operator)
    const id = item.title === title ? item.id : item?.subs?.filter(s => s.title === title)[0].id;

    // Return the id
    return id;
  }
  // Return undefined if not found
  return undefined;
}


console.log("Id: ", findId("Item 3"));
console.log("Id: ", findId("Item 2-3"));
console.log("Id: ", findId("Item 2-1"));
console.log("Id: ", findId("Not Found"));

The last one returns undefined as intended, since the title is not included in the array.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!