lodash - 如何根据子键的值返回父级?
问题描述
我试图找到一种在数组中返回父母的方法。我已经尝试过pickBy
堆栈上的其他解决方案,但它要么返回整个父数组,要么什么都不返回。
这就是我的数组的样子,我想根据tags
.
{
'fraga': "Question 1",
'svar' : "This is this explanation",
'tags' : ['knowledge'],
},
{
'fraga': "Question 2",
'svar' : "This is this explanation for question 2",
'tags' : ['knowledge', 'code'],
},
因此,如果我想要带有标签的父母,knowledge
我会得到“问题 1”和“问题 2”,但如果我想要带有标签的父母,code
我只会得到“问题 2”。
解决方案
我写了一个简单的包装函数,以防你多次调用它来分别搜索多个标签,但你可以很容易地在函数中使用 Lodash 代码。
const arr = [
{
'fraga': "Question 1",
'svar' : "This is this explanation",
'tags' : ['knowledge'],
},
{
'fraga': "Question 2",
'svar' : "This is this explanation for question 2",
'tags' : ['knowledge', 'code'],
}
];
console.log(getByTag(arr, 'knowledge'));
console.log(getByTag(arr, 'code'));
function getByTag(objectArray, tagName) {
return _.filter(objectArray, (obj) => _.includes(obj.tags, tagName));
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>
推荐阅读
- swift - 在 ViewModel SwiftUI 类中存储 Firebase 云消息传递令牌
- javascript - 如何制作这样的 4 位数代码字段?
- python - 将 python 请求转换为 aiohttp 并为其添加错误处理
- android - 在 MoviesApp 上实现收藏夹功能
- mysql - Rails 5 API - 即使无法建立与数据库的连接,也加载静态页面
- c# - 如何在 Unity 中制作动画天空盒?
- c - Makefile:尽管所有文件都在那里
- html - 如何在同一行对齐标题和无序列表
- css - CSS:无法让滚动条出现在水平滚动 DIV 上
- c# - Azure 函数访问存储帐户