【发布时间】:2021-04-03 00:43:46
【问题描述】:
目标
我想在 TypeScript 中开发一个中间件,用于过滤 REST API 的响应并仅返回已定义的属性。 它应该通用,即独立于特定实体。它们的属性和确切的深度(例如,具有任意数量的关系)都不一定是已知的。
示例
一个作者有任意数量的文章和任意数量的 cmets。
[
{
"name": "John Doe",
"email": "john@doe.com",
"articles": [
{
"title": "Lalilu 1",
"text:": "la li lu",
"comments": [
{
"author": "Bendthatdict Cumberstone",
"text": "Great article!"
},
{
"author": "Bendthatdict Cumberstone",
"text": "Great article!"
}
]
},
{
"title": "Lalilu 1",
"text:": "la li lu",
"comments": [
{
"author": "Bendthatdict Cumberstone",
"text": "Great article!"
},
{
"author": "Bendthatdict Cumberstone",
"text": "Great article!"
}
]
}
]
},
{
"name": "Jane Doe",
"email": "jane@doe.com",
"articles": [
{
"title": "Lalilu 1",
"text:": "la li lu",
"comments": [
{
"author": "Bendthatdict Cumberstone",
"text": "Great article!"
},
{
"author": "Bendthatdict Cumberstone",
"text": "Great article!"
}
]
},
{
"title": "Lalilu 1",
"text:": "la li lu",
"comments": [
{
"author": "Bendthatdict Cumberstone",
"text": "Great article!"
},
{
"author": "Bendthatdict Cumberstone",
"text": "Great article!"
}
]
}
]
}
]
现在我想指定它应该返回除每篇文章的“文本”和每条评论的“作者”之外的所有内容。
使用 glob 表示法的语法可能如下所示:
select("*,!articles.text,!articles.comments.author")
方法
对于对象和嵌套对象来说非常简单,例如使用“lodash”的pick()和omit(),但是当数组进入游戏时我失败了。 我做了一些研究,发现了 json-mask、node-glob 或 glob-object 等软件包,但它们都不能完全满足我的需求,我无法将它们组合起来取得成功。
问题
一般过滤任意嵌套的 JSON 与任意数量的其他对象/数组的最有效方法是什么? 另外,TypeScripts 类型系统如何发挥优势?
我将非常感谢通用编码方法,甚至是已经可以做到这一点的包的提示!
【问题讨论】:
-
可能您需要坐下来为此编写一个漂亮的递归函数,该函数会检查嵌套属性并相应地调用数组、对象递归函数,看不到打字稿可以提供帮助的方法明确的。
标签: javascript json typescript data-structures filter