Rob Terrell
Rob Terrell

Reputation: 2562

Searching through array of objects that contain arrays of objects efficiently

I am currently searching through an array of objects that contains an array of objects, the data structure looks like the following:

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

The expected result is to search through the categories array for a given category name (in this case 'general') and then search through the fields for a given field name (in this case 'rating') and return the type associated with the field. I have achieved this by doing the following:

 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])

I am wondering if there is a more efficient way to search through the array of objects within an array of objects, possibly with the type not being returned in an array

Upvotes: 1

Views: 30

Answers (1)

Unmitigated
Unmitigated

Reputation: 89314

If you only need the first match, you can use Array#find along with optional chaining.

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);

Upvotes: 1

Related Questions