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?
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.