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",
subs: [
{
id: 100,
title:"Item 2-2-1"
}, {
id: 110,
title:"Item 2-2-2"
}, {
id: 120,
title:"Item 2-2-3"
}
]
}, {
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.
findId(title, list)
function. Its purpose is to iterate the list received in the second parameter, look for the title in each element and if there is a match it returns the id, otherwise it checks if there aresubs
in the element and in that case it is called recursively thefindId
function using the subs of the element as a list. If an element is found, its id is returned, otherwise the iteration continues.
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
function findId(title, list) {
for (const _item of list) {
if (_item.title === title) {
// Return some top-level id
return _item.id;
// If the item is not the one, check if it has subs
} else if (_item?.subs) {
// Use _item.subs as a list, calling the function recursively
const subId = findId(title, _item.subs);
// Return some nested subId if found
if (subId !== undefined) return subId;
}
}
// Return undefined if not found
return undefined;
}
var myData = [
{
id: 0,
title: "Item 1"
},
{
id: 1,
title: "Item 2",
subs: [
{
id: 10,
title: "Item 2-1",
subs: [
{
id: 100,
title: "Item 2-2-1"
}, {
id: 110,
title: "Item 2-2-2"
}, {
id: 120,
title: "Item 2-2-3"
}]
}, {
id: 11,
title: "Item 2-2"
}, {
id: 12,
title: "Item 2-3"
}]
},
{
id: 2,
title: "Item 3"
},
// more data here
];
console.log("Id: ", findId("Item 2", myData));
console.log("Id: ", findId("Item 2-1", myData));
console.log("Id: ", findId("Item 2-2-2", myData));
console.log("Id: ", findId("Wrong Title", myData));
console.log("Id: ", findId("Item 2", myData));<br/>
console.log("Id: ", findId("Item 2-1", myData));<br/>
console.log("Id: ", findId("Item 2-2-2", myData));<br/>
console.log("Id: ", findId("Wrong Title", myData));<br/>
The last one returns undefined
as intended, since the title is not included in the array.