簡體   English   中英

有效地搜索包含對象 arrays 的對象數組

[英]Searching through array of objects that contain arrays of objects efficiently

我目前正在搜索包含對象數組的對象數組,數據結構如下所示:

const category = 'general'
const field = 'rating'

const schema = {
  categories: [
    {
      name: 'general',
      label: 'General',
      fields: [
        {
          name: 'id',
          label: 'Market Street ID',
          type: 'string'
        },
        {
          name: 'rating',
          label: 'Rating',
          type: 'number'
        }
      ]
    },
    {
      name: 'location',
      label: 'Location',
      fields: [
        {
          name: 'search',
          label: 'Query Parameters',
          type: 'string'
        }
      ]
    }
  ]
}

預期的結果是在類別數組中搜索給定類別名稱(在本例中為“general”),然后在字段中搜索給定字段名稱(在本例中為“rating”)並返回與該字段關聯的類型. 我通過執行以下操作實現了這一點:

 const type = schema.categories
        .filter((cat) => cat.name === category)
        .map((cat) => {
          const fieldData = cat.fields.find((f) => f.name === field)
          return fieldData.type
        })

console.log(type[0])

我想知道是否有更有效的方法來搜索對象數組中的對象數組,可能類型未在數組中返回

如果您只需要第一個匹配項,則可以使用Array#find可選鏈接

 const category="general",field="rating",schema={categories:[{name:"general",label:"General",fields:[{name:"id",label:"Market Street ID",type:"string"},{name:"rating",label:"Rating",type:"number"}]},{name:"location",label:"Location",fields:[{name:"search",label:"Query Parameters",type:"string"}]}]}; const type = schema.categories.find(cat => cat.name === category)?.fields.find(f => f.name === field).type; console.log(type);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM