I have a query syntax which needs to be applied to a json object and return an array of valid paths in the json object.
For example, with a query as such:
People.[].Dependents.[]
And the following JSON object:
{
"People": [
{
"FirstName": "John",
"LastName": "Doe",
"Dependents": [
{
"Name": "John First Dep"
},
{
"Name": "John Second Dep"
}
]
},
{
"FirstName": "Jane",
"LastName": "Smith",
"Dependents": [
{
"Name": "Jane First Dep"
}
]
}
]
}
The result would be:
[
"People.0.Dependents.0",
"People.0.Dependents.1",
"People.1.Dependents.0",
]
I'm currently trying to do this as succinctly as possible. Any attempt I've made thus far has resulted in far too much code and is incredibly hard to follow. Am I missing something obvious?
Edit: Current Code:
function expandQuery(data, path) {
const parts = path.split("[]").map(s => _.trim(s, "."));
const [outer, ...right] = parts;
const inner = _.join(right, ".[].");
let groupData = _.get(data, outer, []);
if (!_.isArray(groupData)) {
groupData = [groupData];
}
const groupLength = groupData.length;
let items = [];
for (let ind = 0; ind < groupLength; ind++) {
items.push(outer + "." + ind.toString() + "." + inner);
}
const result = [];
for (let ind = 0; ind < items.length; ind++) {
const item = items[ind];
if (item.includes("[]")) {
result.push(...expandQuery(data, item));
} else {
result.push(_.trim(item, "."));
}
}
return result;
}
I'm looking specifically to make this shorter.