[英]Compare Nested Object Field to Array List in Javasacript/Lodash
我有以下2條數據:
用戶:
[
{id:1, food:{id:2, name:"coffee"} },
{id:2, food:{id:3, name:"tea" } },
{id:3, food:{id:5, name:"salad"} }
]
食物清單:
[2,3]
我當前正在使用react,我需要過濾掉用戶以僅顯示那些來自FoodList數組具有食物ID的用戶。
我在Lodash中嘗試了類似的方法:
var filtered = _.some(users.food.id, foodList);
這是不正確的,因為users.food.id無效。 有沒有一種方法可以將嵌套對象數組與javascript中的列表進行比較?
有一個不錯的簡短的lodash解決方案來解決此問題,如果您已經在使用lodash,可以使用它。
索引使用值_.keyBy()
並且只有那些在提取footList
使用_.at()
var data = [{ id: 1, food: { id: 2, name: "coffee" } }, { id: 2, food: { id: 3, name: "tea" } }, { id: 3, food: { id: 5, name: "salad" } }] var foodList = [2,3]; var result = _(data) // start the chain .keyBy('id') // index the items by key .at(foodList) // get the items .value(); // return the result array console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.2/lodash.min.js"></script>
這是簡單的任務,無需任何庫即可完成。 您可以只使用filter()
和indexOf()
var data = [ {id:1, food:{id:2, name:"coffee"} }, {id:2, food:{id:3, name:"tea"} }, {id:3, food:{id:5, name:"salad"} } ] var arr = [2,3]; var result = data.filter(e => arr.indexOf(e.food.id) != -1) console.log(result)
你可以使用_.filter
和_.includes
從lodash。
var users = [{ id: 1, food: { id: 2, name: "coffee" } }, { id: 2, food: { id: 3, name: "tea" } }, { id: 3, food: { id: 5, name: "salad" } }], foodList = [2, 3], result = _.filter(users, u => _.includes(foodList, u.food.id)); console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"></script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.