繁体   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