Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/webpack/2.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 如何按数组元素筛选集合_Javascript_Lodash - Fatal编程技术网

Javascript 如何按数组元素筛选集合

Javascript 如何按数组元素筛选集合,javascript,lodash,Javascript,Lodash,我有以下格式的数组 "categories": [ { "type": "A", "subtype": [ "X", "Y", "Z", "D", "E" ], }, { "type": "B", "Subtypes": [ "0", "1", "2",

我有以下格式的数组

"categories": [
  {
     "type": "A",               
     "subtype": [
        "X",
        "Y",
        "Z",
        "D",
         "E"           
     ],

  },
  {
     "type": "B",
     "Subtypes": [
        "0",
        "1",
        "2",
        "3",
        "4",
        "5"
     ],        
  },
  {
     "type": "C",         
     "includeConnectionTypes": [
        "@",
        "#",
        "$"
     ],
}]
我有第二个数组B

B = ["C","A"]

现在,如何基于数组B中的元素筛选类别数组中的元素

我想这就是您所需要的:
.filter

_.filter(categories, (item => B.indexOf(item.type)>= 0));
ES5

var result = categories.filter(function (item) {
    return B.indexOf(item.type) > -1;    
});
ES6

var result = categories.filter(item => B.indexOf(item.type) > -1);
此语句将检查“categories”数组的每个元素,如果其类型是数组B的元素,则将其推送到“result”数组

“indexOf”方法返回数组中某个元素的索引,如果该数组不包含该元素,该方法将返回-1

参考:

它是一个数组,现在B也是数组

var B = ["C","A"]

 var result=categories.filter(function(d){
    return B.indexOf(d.type)!=-1;
 });

“结果”包含您的预期结果。

Array.prototype.filter
Array.prototype.prototype的绑定用法的组合。一些
应该是一种可读性很好的方法,还可以通过一个单独的特定函数(如
doesCategoryTypeMatchAnyBoundType
)进行代码重用,与结合了
过滤器
indexOf
的其他方法/解决方案不同,不需要“知道”过滤器类型列表的引用(给定示例中有
B

//Q:我正在使用以下格式的数组。。。
变量类别=[{
“类型”:“A”,
“子类型”:[“X”、“Y”、“Z”、“D”、“E”]
}, {
“类型”:“B”,
“子类型”:[“0”、“1”、“2”、“3”、“4”、“5”]
}, {
“类型”:“C”,
“includeConnectionTypes”:[“@”、“#”、“$”]
}];
// ... 我有第二个阵列。。。
变量类型列表=[“C”,“A”];
// ... 现在,如何基于
//元素在`类型列表“。。。数组。。。
//A:Array.prototype.filter和
//`Array.prototype.some`的绑定用法应该是
//一个可读性很好的方法。。。
函数doesCategoryTypeMatchAnyBoundType(categoryItem){
返回this.some(函数(类型){return(categoryItem.type==type);});
}
var filteredCategoryList=categories.filter(doesCategoryTypeMatchAnyBoundType,typeList);
log(“filteredCategoryList:”,filteredCategoryList)

.as控制台包装{max height:100%!重要;top:0;}
A[t]。类型===B[i]?。。。。。。。这是您所需要的?您可以阅读关于是否有任何lodash函数可以执行相同的操作?@POM。。。关于基于lodash的解决方案,请参见Kai和@POM。我只需更新我的答案,以获得更正确的答案;)!
var B = ["C","A"]

 var result=categories.filter(function(d){
    return B.indexOf(d.type)!=-1;
 });