1

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

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.