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

180
Visualizações
Cleanest solution for extracting a specific index from a path

If I have a path of an object:

const carPath = "data.factories[0].categories[0].cars[0]";

What's the cleanest way to extract factory index, category index and car index? The way I managed to do it is by:

const factoryIndex = carPath.match(/data.factories\[(\d+)\]/)[1]
const categoryIndex = carPath.match(/categories\[(\d+)\]/)[1]
const carIndex = carPath.match(/cars\[(\d+)\]/)[1]

I just take the second value which is captured by (\d+).

Is it possible to target a specific index inside the square brackets with using a global flag so that it returns only one value, which is the index? Or maybe there's even another way?

My scribbles: https://jsfiddle.net/fa4c0myg/1/

Dummy data:

{
    data: {
        factories: [
            {
                name: "Factory1",
                categories: [
                    {
                        name: "Category1",
                        cars: [
                            {name: "Car1"}
                        ]
                    }
                ]
            }
        ]
    }
}
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

A single regular expression that captures all of those indicies would work.

const carPath = "data.factories[5].categories[6].cars[7]";
const [, // ignore the whole match - only use the capture groups
  factoryIndex,
  categoryIndex,
  carIndex,
] = carPath.match(/data\.factories\[(\d+)\]\.categories\[(\d+)\]\.cars\[(\d+)\]/);
console.log(factoryIndex, categoryIndex, carIndex);

Or, if there aren't any other numbers, just:

const carPath = "data.factories[5].categories[6].cars[7]";
const [
  factoryIndex,
  categoryIndex,
  carIndex,
] = carPath.match(/\d+/g);
console.log(factoryIndex, categoryIndex, carIndex);

If the match might not exist, test for whether the match failed before extracting from the result first.

const match = carPath.match(/...)
if (!match) {
  // error
} else {
  // extract from match
}
about 4 years ago · Juan Pablo Isaza 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