【发布时间】:2022-01-13 18:39:04
【问题描述】:
我在一个数组中有一堆内容,类型为:
export interface StaticContent {
level : number,
id : string,
title: string,
content : string[] | StaticContent[],
}
我正在尝试搜索要查询的 id 是内容对象的子元素的对象。我想我可能把界面设置错了,但我有心理障碍。
有什么想法吗?
例子:
data = [
{
level: 0,
id: 'first-element',
title: 'Title of the first element'
content: [
`I am some random string of content`
]
},
{
level: 1,
id: 'second-element',
title: 'Title of the second element'
content: [
{
level: 0,
id: 'first-sub-element',
title: 'Title of first sub element'
content: [
` I am some content attached to the first sub element `
]
}
}]
let idToFind = 'first-sub-element'
let element = data.find(t => t.id === idToFind)
let title = element.title
在这个例子中,结果是一个未定义的元素。
我期待
element = {
level: 0,
id: 'first-sub-element',
title: 'Title of first sub element'
content: [
` I am some content attached to the first sub element `
]
}
}
【问题讨论】:
-
你的代码有什么问题?你期待什么结果?
-
在上面的例子中,我会得到一个未定义的元素。我希望从第二个元素接收内容数组中的整个第一个元素。
-
请在您的帖子中添加预期结果
-
data没有 id=first-sub-element 的元素。 array.find 只查找第一级数组。 -
我需要一个搜索嵌套元素的方法
标签: javascript arrays typescript