2016-12-07 91 views
0

,我有以下2個數據:比較嵌套對象字段來數組列表中Javasacript/Lodash

用戶:

[ 
    {id:1, food:{id:2, name:"coffee"} }, 
    {id:2, food:{id:3, name:"tea" } }, 
    {id:3, food:{id:5, name:"salad"} } 
] 

foodList:

[2,3] 
我目前使用

反應,我需要篩選出的用戶只顯示FoodList數組的食物ID。

我試着在Lodash是這樣的:

var filtered = _.some(users.food.id, foodList); 

這是不正確,因爲users.food.id無效。有沒有辦法將嵌套的對象數組與javascript中的列表進行比較?

回答

2

有一個很好的和短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>

2

您可以使用Array.prototype.filter

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

MDN documentation

1

這是簡單的任務,你可以在沒有任何庫做。你可以只用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)

1

你可以使用_.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>