[英]Find a value in an array of populated objects mongdb - lodash
也許這個問題是重復的或以不同的方式問了幾次,但仍然沒有解決我的問題。 我正在創建從mongodb返回10,000個填充對象的nodejs api。 我想根據對象過濾數組。
{color: red}
我如何使用lodash過濾器返回包含指定過濾器對象的數組。
[
{
"value": 200,
"newEle": {
"gradient": "true",
"mode": {
"color": "red"
}
}
},
{
"value": 100,
"newEle": {
"gradient": "false",
"mode": {
"color": "blue"
}
}
}
]
如果您專門嘗試僅按顏色進行過濾,則可以使用香草JS的.filter()
將所有具有red
的color
屬性的對象放入新數組中:
const arr = [ { "value": 200, "newEle": { "gradient": "true", "mode": { "color": "red" } } }, { "value": 100, "newEle": { "gradient": "false", "mode": { "color": "blue" } } } ], color = "red", res = arr.filter(obj => obj.newEle.mode.color === color); console.log(res);
如果您想專門使用lodash
,可以使用_.filter()
:
const arr = [ { "value": 200, "newEle": { "gradient": "true", "mode": { "color": "red" } } }, { "value": 100, "newEle": { "gradient": "false", "mode": { "color": "blue" } } } ], color = "red", res = _.filter(arr, obj => obj.newEle.mode.color === color); console.log(res);
<script src="https://cdn.jsdelivr.net/lodash/4.16.4/lodash.min.js"></script>
使用lodash時,就這么簡單。
let filtered_array = _.filter(myArr, { color: 'red' });
但是,由於您嵌套了嵌套對象,因此您需要創建一個訪問嵌套值的謂詞。 您可以使用數組來執行此操作。
let filtered_array = _.filter(myArr, ['newEle.mode.color', 'red']);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.