Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 使用Lodash筛选具有数组字段的对象数组_Javascript_Arrays_Filter_Lodash - Fatal编程技术网

Javascript 使用Lodash筛选具有数组字段的对象数组

Javascript 使用Lodash筛选具有数组字段的对象数组,javascript,arrays,filter,lodash,Javascript,Arrays,Filter,Lodash,我有两个数据集: 人民: [ {id:1, selected:[1,2,3,4]}, {id:2, selected:[1,2,3,4,5]}, {id:3, selected:[11]}, {id:4, selected:[1,2,5]} ] 选定阵列: [1,2,3] 我可以通过selectedArray过滤People.id: _(People).indexBy('id').at(selectedArray).value(); 但对于如何过滤一个没有表

我有两个数据集:

人民:

[
    {id:1, selected:[1,2,3,4]},
    {id:2, selected:[1,2,3,4,5]},
    {id:3, selected:[11]},
    {id:4, selected:[1,2,5]}
]
选定阵列:

[1,2,3]
我可以通过
selectedArray
过滤
People.id

_(People).indexBy('id').at(selectedArray).value();
但对于如何过滤一个没有表示为单个值的字段,我感到困惑。例如,
People[0]。选择了作为整数数组的

selectedArray
中的“所选人员”字段中,是否可以仅显示包含至少1个整数的
人员
对象

我试过这个:

_.intersection(selectedArray, _.map(People, 'selected'));
我最终想要一个
People
对象数组,其中所选字段仅限于
selectArray
的整数。因此,结果将是:

[
    {id:1, selected:[1,2,3]},
    {id:2, selected:[1,2,3]},
    {id:4, selected:[1,2]}
]

我目前正在通过一个for循环来计算这个,但我认为这不是一个很好的解决方案,我想知道是否有比遍历整个对象数组更优雅的方法

您可以在过滤器中使用Array.some(香草js):

var sel=[1,2,3]
var arr=[
{id:1,选中:[1,2,3,4]},
{id:2,选中:[1,2,3,4,5]},
{id:3,已选定:[11]},
{id:4,已选定:[1,2,5]}
]
var res=arr.filter(x=>x.selected.some(y=>sel.some(z=>z==y)))。
地图(x=>{
x、 selected=x.selected.filter(y=>sel.some(z=>z==y));
返回x;
})

console.log(res)
您可以在过滤器中使用Array.some(香草js):

var sel=[1,2,3]
var arr=[
{id:1,选中:[1,2,3,4]},
{id:2,选中:[1,2,3,4,5]},
{id:3,已选定:[11]},
{id:4,已选定:[1,2,5]}
]
var res=arr.filter(x=>x.selected.some(y=>sel.some(z=>z==y)))。
地图(x=>{
x、 selected=x.selected.filter(y=>sel.some(z=>z==y));
返回x;
})

console.log(res)
这与我想要的非常接近。根据该结果,是否有方法过滤每个选定的属性并将其限制为sel的值?因此,我不会得到{“id”:2,“selected”:[1,2,3,4,5]},而是得到{“id”:1,“selected”:[1,2,3]}。目前我所做的一切都是遍历,我发现lodash是简化代码的一个非常好的解决方案。谢谢您可以映射输出并过滤所选阵列,我在第一个案例中添加了一个示例我有一点需要学习,但答案非常清楚,再次感谢!这是非常接近我要找的。根据该结果,是否有方法过滤每个选定的属性并将其限制为sel的值?因此,我不会得到{“id”:2,“selected”:[1,2,3,4,5]},而是得到{“id”:1,“selected”:[1,2,3]}。目前我所做的一切都是遍历,我发现lodash是简化代码的一个非常好的解决方案。谢谢您可以映射输出并过滤所选阵列,我在第一个案例中添加了一个示例我有一点需要学习,但答案非常清楚,再次感谢!