简体   繁体   English

用另一个数组过滤 object 数组

[英]Filtering an object array with another array

I am having a filtering problem..我有一个过滤问题..

objArray is the array that needs to be filtered. objArray 是需要过滤的数组。 selectedNames is an array that contains the values that I want to find in objArray. selectedNames 是一个数组,其中包含我想在 objArray 中查找的值。 I need to fetch all objects that have one or more values from selectedNames in their "names" property (an array).我需要从其“名称”属性(数组)中的 selectedNames 中获取具有一个或多个值的所有对象。

The output I am trying to get is:我要获取的 output 是:

let result = [{names:["A","B","C","D"]},
              {names:["A","B"]},
              {names:["A","D"]}
             ]

Here is a simplified version of my code:这是我的代码的简化版本:

let objArray = [{names:["A","B","C","D"]},
                {names:["C","D"]},
                {names:["C","D","E"]},
                {names:["A","B"]},
                {names:["A","D"]}
               ]

let selectedNames = ["A","B"]

result = this.objArray .filter(obj => {
   return this.selectedNames.includes(obj.names)
}


My code seems to work fine if names attribute was a single value and not an array.如果 names 属性是单个值而不是数组,我的代码似乎可以正常工作。 But I can't figure out how to make it work on an array.但我不知道如何让它在数组上工作。

Any help is more than welcome任何帮助都非常受欢迎

You could do something like this.你可以做这样的事情。 Filtering the array based on the names property having 'some' value be included in the selectedNames array.根据 selectedNames 数组中包含“some”值的names属性过滤数组。 ... ...

objArray.filter(obj => obj.names.some(name => selectedNames.includes(name)));

[ Edit ] As @RadicalTurnip pointed out, this is not performant if the selectedNames is too large. [编辑] 正如@RadicalTurnip 指出的那样,如果 selectedNames 太大,则性能不佳。 I would suggest that you use an object. Ex我建议您使用 object.Ex

...
const selectedNamesMap = selectedNames.reduce((p,c) => ({...p, [c]: true}), {});
objArray.filter(obj => obj.names.some(name => selelectedNamesMap[name]));

Overkill, but if the arrays are really large (millions of elements) then you are better of using regular for loop and not array methods.矫枉过正,但如果 arrays 真的很大(数百万个元素),那么您最好使用常规 for 循环而不是数组方法。

This result is not performant scaled up, but I don't know that there is any way to ensure that it will be performant unless you know more information (like the names are already sorted).这个结果没有按比例放大,但我不知道有什么方法可以确保它的性能,除非你知道更多信息(比如名字已经排序)。 That being said, you just missed one more piece of logic.话虽这么说,你只是错过了一个逻辑。

result = this.objArray.filter(obj => {
  let toReturn = false;
  obj.names.forEach(name => {
    if (this.selectedNames.includes(name))
      toReturn = true;
    };
  };
  return toReturn;
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM