在对象数组中find需要的元素的最佳方法

我有我的class的对象的数组。 我的类有variables的名称是唯一的每个对象创build。 现在,我想查找名称为“test”的数组中的对象。 我想尝试像创build第二个数组与名称作为元素,当我在我的第一个数组中创build新的对象创build第二个数组中的对象,以便他们共享索引号。 像这样的东西:

arrayOfObjects.push(new obj("test")); arrayOfNames.push("test"); function findIndexNumberOf(name){ for(var i = 0; i < arrayOfNames.length; i++){ if(arrayOfNames[i] === name) return i; } } 

但我认为这是相当强大的解决scheme,所以我想知道有没有更好/更聪明/更快的方式做到这一点。

如果你想find一个项目的索引,通常使用indexOf最简单:

 const haystack = ["this", "is", "a", "test"]; const needle = "this"; const result = haystack.indexOf(needle); 

但是,这将与原始types一起工作。 假设你有一个对象数组,比较它们将需要不同的方法。 这里有一些单线:

 const haystack = [new String("this"), new String("is"), new String("a"), new String("test")]; const needle = "test"; const result1 = haystack.indexOf(haystack.filter(item => item == needle)[0]); const result2 = haystack.indexOf(haystack.filter(item => item.toString() === needle.toString())[0]); const result3 = haystack.map(item => item.toString()).indexOf(needle.toString()); const result4 = haystack.indexOf(haystack.find(item => item.toString() === needle.toString())); 

result1使用==运算符过滤haystack,因此忽略了比较值实际上是不同types的事实。 滤波后的数组的第一个元素被送到indexOf 。 这将允许你使用一个原始的string作为针,并通过对象的大堆search。

result2使用相同的方法,但将两个比较值都转换为原始string,确保它们都是相同的types。 这将使您能够在干草堆和针头中宽松地混合和匹配基元和String对象。

result3将所有haystack值映射到原始string,然后在该新的基元数组上使用indexOf 。 我还添加了toString到针,以确保它也是一个原始的。 这与您的方法类似,但每次search针时都会运行映射。 这可能不是最理想的。

result4使用Array.prototype.find在干草result4定位目标对象,然后将结果提供给indexOf 。 这可能是最快的,但我没有经验数据来支持。

现在,如果你想find实际的项目 ,而不仅仅是它的索引,你最好使用Array.prototype.find

 const result = haystack.find(item => item == needle); 

或者,如果两者都是String对象:

 const result = haystack.find(item => item.toString() === needle.toString()); 

您可以使用Arrays对象的find方法 :

 const myObject = arr.find(o => o.name === 'the_name_you_search');