javascript - 如何过滤对象数组的数组?

标签 javascript arrays angular

我正在尝试过滤对象数组的数组,但它不起作用。

   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 只是决定是否保留现有内容,而不会改变那里有什么。 map 确实如此。像这样的事情:

  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"}], undefined],
];
const filterText = "target";

const constructedGrid = fullGrid
      // Map the inner array to one that only has matching entries
      .map(array => array.filter(obj => obj && obj[0] && obj[0].name === filterText))
      // Remove blank inner arrays from the overall array
      .filter(array => array.length);
console.log(constructedGrid);
.as-console-wrapper {
    max-height: 100% !important;
 }

请注意,如果您想从外部数组中删除完全空的数组,则只需要第二个过滤器。如果您想离开他们,只需删除该通话即可。 编辑:从您对我的问题的回复来看,您似乎想删除第二个 .filter

注意第一个filter中的守卫,即obj && obj[0] &&部分。它在那里是因为你说有时数组条目是“空的”。我不知道您的字面意思是空(稀疏数组)还是未定义的条目。如果您的字面意思是(稀疏数组),则不需要防护,但最好拥有它。

从 ES2020 开始,您可以使用可选的链接运算符:

.filter(obj => obj?.[0]?.name === filterText)
如果 objnull

obj?.[0]?.name 计算结果为 undefined >未定义,或obj[0]null未定义;否则,它的计算结果为 obj[0].name 。由于 undefined === filterText 将为 false,因此带有 nullundefined obj 的条目将被排除。不过,新功能再次强调,如果您不进行转译,则需要检查目标浏览器的支持情况。

关于javascript - 如何过滤对象数组的数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61406558/

相关文章:

php - Javascript 和 PHP 将数据导出到文件

arrays - 为什么Powershell会合并数组数组?

java - 滑动拼图,开关图标

angular - 无法绑定(bind)到 'formControl',因为它不是 'input' 的已知属性 - Angular2 Material Autocomplete 问题

javascript - 托管在不同服务器上时刷新 iframe

javascript - 修改日历,以便在单击日期时打开注释

javascript - 保持多选jquery的滚动位置

c - 释放结构数组

html - Angular 6 bootstrap 4 - 导航栏品牌标志在向下滚动时不会改变

Angular 2如何从输入中删除粘贴的内容