[英]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.