簡體   English   中英

比較嵌套對象字段與Javasacript / Lodash中的數組列表

[英]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中的列表進行比較?

您可以使用Array.prototype.filter

const result = users.filter(e => foodList.includes(e.food.id));

MDN文檔

有一個不錯的簡短的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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM