如何在路线中拆分任意 JavaScript 对象,如树
How to split an arbitrary JavaScript object in routes, like a tree
我在我的快速服务器中收到一组作为组合对象的过滤器。为了创建查询,我得出了将每个对象路由拆分为单独的键数组的结论。
示例:
$and: {
age: [21, 22],
name: {
$like: "Alice"
}
}
我想要的:
[$and,age,[21, 22]]
[$and,name,$like,"Alice"]
任何解决此问题的线索将不胜感激。
这应该有效。它使用递归函数遍历对象的每个项目并为每个值创建一个路由。
const obj = {
$and: {
age: [21, 22],
name: {
$like: "Alice"
}
}
};
function getRoute(o) {
const result = [];
const route = (subObj, keyIndex = 0, path = []) => {
const keys = Object.keys(subObj);
if (typeof subObj === 'object' && !Array.isArray(subObj) && keys.length > 0) {
while (keyIndex < keys.length) {
route(subObj[keys[keyIndex]], 0, [...path, keys[keyIndex]]);
keyIndex++;
}
} else {
result.push([...path, subObj]);
}
};
route(o);
return result;
}
console.log(JSON.stringify(getRoute(obj))); // Returns an string
console.log(getRoute(obj)); // Returns an array
我在我的快速服务器中收到一组作为组合对象的过滤器。为了创建查询,我得出了将每个对象路由拆分为单独的键数组的结论。
示例:
$and: {
age: [21, 22],
name: {
$like: "Alice"
}
}
我想要的:
[$and,age,[21, 22]]
[$and,name,$like,"Alice"]
任何解决此问题的线索将不胜感激。
这应该有效。它使用递归函数遍历对象的每个项目并为每个值创建一个路由。
const obj = {
$and: {
age: [21, 22],
name: {
$like: "Alice"
}
}
};
function getRoute(o) {
const result = [];
const route = (subObj, keyIndex = 0, path = []) => {
const keys = Object.keys(subObj);
if (typeof subObj === 'object' && !Array.isArray(subObj) && keys.length > 0) {
while (keyIndex < keys.length) {
route(subObj[keys[keyIndex]], 0, [...path, keys[keyIndex]]);
keyIndex++;
}
} else {
result.push([...path, subObj]);
}
};
route(o);
return result;
}
console.log(JSON.stringify(getRoute(obj))); // Returns an string
console.log(getRoute(obj)); // Returns an array