Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

80
Visualizações
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

about 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

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

about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda