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