简体   繁体   English

带有自定义对象的Typescript数组函数等于

[英]typescript array functions with custom object equals

I want to use array functions (like contains, unique) which check equality with my own equals function. 我想使用数组函数(例如contains,unique),该函数使用我自己的equals函数检查相等性。

For example: 例如:

let arr = [{id:1,..//some more},{id:2,..//some more},{id:3,..//some more}]

I want that this will return true, by using equals function that check the id only: 我希望通过使用仅检查id的equals函数将其返回true:

arr.contains({id:1,....}).

I tried to search by didn't find. 我尝试搜索未找到。

How can I do it? 我该怎么做? and generally how can I use my own equal function in typescript (like equals function in Java). 通常,我如何在打字稿中使用自己的equal函数(例如Java中的equals函数)。

You cannot change the equality check used by array functions like includes or indexOf . 您不能更改数组函数(例如includesindexOf使用的相等性检查。 But other array functions let you use a callback instead: 但是其他数组函数让您可以使用回调:

  • find - Finds the first entry in the array for which your callback returns a truthy value find -查找数组中的第一个条目,你的回调函数返回一个值truthy
  • findIndex - Finds the index of the first entry in the array for which your callback returns a truthy value findIndex查找您的回调为其返回真值的数组中第一个条目的索引
  • some - Loops through an array calling your callback until it returns a truthy value (in which case some stops and returns true ); some -遍历数组调用回调函数,直到它返回一个值truthy(在这种情况下, some停止转动,返回true ); if your callback never returns a truthy value, some returns false . 如果您的回调从不返回真实值,则some返回false
  • every - Loops through an array calling your callback until it returns a falsy value (in which case every stops and returns false ); every -通过数组调用回调函数,直到它返回一个值falsy循环(在这种情况下, every停止转动,返回false ); if your callback never returns a falsy value, every returns true . 如果您的回调从未返回虚假值,则every返回true

All of these are described, with linked detailed descriptions, on the MDN array page . 所有这些都在MDN阵列页面上以链接的详细说明进行了描述。

So for example, "contains" with custom equality would be some : 因此,例如,具有自定义等式的“包含”将是some

 const a = [ {id: 1}, {id: 2}, {id: 3} ]; console.log("Has 1? " + a.some(e => e.id == 1)); console.log("Has 4? " + a.some(e => e.id == 4)); 

You can use find and test that the value returned is not undefined 您可以使用查找并测试返回的值是否未定义

Example: 例:

let arr = [{id: 1, test: '1'}, {id: 2, test: '2'}];
const customEqual = i => i.id === 1;
const containsItemWithId1 = arr.find(customEqual) !== undefined;

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

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