[英]how to filter an array on condition like SQL IN clause using lodash?
我正在嘗試使用 lodash 過濾數組中存在的數據。 我正在嘗試像 SQL IN 子句一樣過濾。
ex: - select * from Test where id IN (2,4,5,67);
JSON:
storedData = [
{
"id" : 1,
"name" : "ABC"
},
{
"id" : 2,
"name" : "XYZ"
},
{
"id" : 3,
"name" : "BVX"
},
{
"id" : 4,
"name" : "OOO"
}
]
搜索條件:
[2,4,5,67]
所需輸出:
output = [
{
"id" : 2,
"name" : "XYZ"
},
{
"id" : 4,
"name" : "OOO"
}
]
下面是我試圖實現的代碼
output = _.filter(storedData, (value) => {
return value.id == 2 || value.id == 4 || value.id == 5 || value.id == 67
});
你能幫我如何過濾 IN 子句嗎?
您可以使用intersectionWith
找到兩個數組之間的intersectionWith
,這允許您提供回調並保留回調為其返回true
的第一個數組中的所有元素。
請參閱下面的示例:
const storedData = [ { "id" : 1, "name" : "ABC" }, { "id" : 2, "name" : "XYZ" }, { "id" : 3, "name" : "BVX" }, { "id" : 4, "name" : "OOO" } ]; const search = [2,4,5,67]; const res = _.intersectionWith(storedData, search, (o, n) => o.id === n); console.log(res);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>
使用.includes
_.filter(storedData, (value) => _.includes(criteria, value.id))
const storedData = [ { id: 1, name: "ABC", }, { id: 2, name: "XYZ", }, { id: 3, name: "BVX", }, { id: 4, name: "OOO", }, ] const criteria = [2, 4, 5, 67] const output = _.filter(storedData, (value) => _.includes(criteria, value.id)) console.log(output)
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.20/lodash.min.js"></script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.