使用JS获得层次数据中的ID
我将层次数据作为树数组:
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
];
我需要在此数组中获得标题的ID。我尝试使用此功能:
console.log(myData.findIndex(item=>item.title==="Item 3"))
但是它对“项目2-2”有害。我应该如何解决这个问题?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我制作了此简单的
findID
方法,以找到标题并返回id
或undefined
作为数据阵列结构的结果。假设每个标题在数组中都是唯一的。
否则只会找到第一个。
看以下
最后一个返回
未定义的
,因为该标题不包括在数组中。I made this simple
findId
method in order to find the title and returns theid
orundefined
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
The last one returns
undefined
as intended, since the title is not included in the array.