繁体   English   中英

查找嵌套元素 Typescript 数组 object

[英]Finding nested elements Typescript Array object

我在一个数组中有一堆内容,类型为:

export interface StaticContent {
  level : number,
  id : string,  
  title: string,
  content : string[] | StaticContent[],
}

我正在尝试搜索 object,其中要查询的 id 是内容 object 的子元素。 我想我可能把界面设置错了,但我有一个心理障碍。

有任何想法吗?

例子:

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 `
       ]
     }
}

您需要使用递归或就地进行递归搜索。

这是递归示例:


function searchInContent(idToFind: string, content: StaticContent[] | string[]): StaticContent | null {   
    for (const c of content) {
       if (typeof c === 'string') continue
 
       // now we can assume that c is StaticContent
       if (c.id === idToFind) {
          // FOUND RESULT
          return c
       } 
   
       // Perform deep search in content
       const result = searchInContent(idToFind, c.content)
       if (result !== null) {
          // stop searching and pass found result
          return result
       }
    }
    return null
}

let idToFind = 'first-sub-element'
let element = searchInContent(data)
let title = element.title

您需要检查content

 const 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 ` ] }, { level: 0, id: 'first-sub-elemeeent', title: 'Title of first sub element', content: [ ` I am some content attached to the first sub element ` ] }] } ]; let idToFind = 'first-sub-element' const result = data.map((t) => { return t.content.find(c => c.id === idToFind); }).filter(x => x);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM