Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/13.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_Arrays_Angular - Fatal编程技术网

Javascript 如何过滤对象数组的数组?

Javascript 如何过滤对象数组的数组?,javascript,arrays,angular,Javascript,Arrays,Angular,我试图过滤对象数组,但它不起作用 constructNewGrid(filterText){ if(searchText == ""){ this.constructedGrid = this.fullGrid; return; } this.constructedGrid = []; this.constructedGrid = this.fullGrid.filter(array => array.f

我试图过滤对象数组,但它不起作用

   constructNewGrid(filterText){
      if(searchText == ""){
        this.constructedGrid = this.fullGrid;
        return;
      }
      this.constructedGrid = [];
      this.constructedGrid = this.fullGrid.filter(array => array.filter(obj => {
        if(obj.name == filterText)
          return obj;
      }));
      console.log(this.constructedGrid);
   }
如果找到正确的对象,我想返回一个数组,但当我控制台记录它时,constructedGrid是同一个数组,但为什么? 代码应该转到第一个数组,应该查找是否存在名称等于筛选器文本的对象。它应该返回带有相应对象的数组,然后检查下一个数组,依此类推

这将是以下格式:

[ 
  [[{name: string}], empty, empty], // array of lenth 3 
  [empty, empty, [{name: string}], empty], // array of length 4 
   ... 
]
如果找到一个对象,则应将其分别推入一个数组中,这样,如果在同一数组中找到两个对象,则应将它们分别放入两个单独的数组中,并且这些对象应位于一个单独的数组中: 结果应该是

[
 [[obj1]],
 [[obj2]],
 ...
]

这对我来说似乎是可能的。有时我遇到一个错误,我的内存不足哈哈…

除了
filter
,你还需要
map
,因为
filter
只是决定是否保留那里的内容,它不会改变那里的内容<代码>映射执行。大概是这样的:

  this.constructedGrid = this.fullGrid
      // Map the inner array to one that only has matching entries
      .map(array => array.filter(obj => obj && obj.name === filterText))
      // Remove blank inner arrays from the overall array
      .filter(array => array.length);
实例:

const fullGrid=[
[{name:“target”}],],
[,null,[{name:“target”}],未定义],
];
常量filterText=“目标”;
const constructedGrid=fullGrid
//将内部数组映射到只有匹配项的数组
.map(array=>array.filter(obj=>obj&&obj[0]&&obj[0].name==filterText))
//从整个阵列中删除空白内部阵列
.filter(数组=>array.length);
console.log(constructedGrid)
。作为控制台包装器{
最大高度:100%!重要;

}
一旦从数组中删除所有空条目,如果该数组完全为空,该怎么办?例如,它甚至没有一个对象?如果是这样的话,我会用ngIf在我的HTML文件中自己处理它:但不仅应该删除空条目,还应该检查对象的属性名是否等于filterText。一个阵列中可以有多个对象。谢谢您的简明回答!不知何故,即使名称完全相同,也找不到对象。你知道问题可能出在哪里吗?我能不能在地图功能中记录我的对象?非常抱歉,格式不对。这将是正确的:在控制台中使用Array[Array(1),Array(1),empty×3],但现在我知道我必须使用map!我自己试试看@罗吉克啊!这里还有另一层阵列。。。我会更新的。最里面的数组总是只有一个长吗?正是整个格式:
[[[[{name:string}],empty,empty],//长度为3的数组[empty,empty,[{name:string}],empty],//长度为4的数组…]