【发布时间】:2018-11-09 14:44:41
【问题描述】:
我有一个查询语法,它需要应用于 json 对象并在 json 对象中返回一组有效路径。
例如,使用这样的查询:
People.[].Dependents.[]
还有以下 JSON 对象:
{
"People": [
{
"FirstName": "John",
"LastName": "Doe",
"Dependents": [
{
"Name": "John First Dep"
},
{
"Name": "John Second Dep"
}
]
},
{
"FirstName": "Jane",
"LastName": "Smith",
"Dependents": [
{
"Name": "Jane First Dep"
}
]
}
]
}
结果是:
[
"People.0.Dependents.0",
"People.0.Dependents.1",
"People.1.Dependents.0",
]
我目前正在尝试尽可能简洁地做到这一点。到目前为止,我所做的任何尝试都导致代码过多,并且难以遵循。我错过了什么明显的东西吗?
编辑:当前代码:
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;
}
我正在特别想缩短这个时间。
【问题讨论】:
-
到目前为止你的尝试是什么?
-
@lumio:添加了一个工作示例
标签: javascript json lodash