Lodash判断集合指定值存在失败,求非Lodash替代实现方案
问题解决:判断集合中是否包含指定国家值
嘿,我来帮你搞定这个问题!首先得说,你之前用_.has的思路完全走错方向啦——这个Lodash方法是用来检查对象是否存在某个属性路径(比如_.has(user, 'address.city')),根本不是用来检测数组里的对象是否包含某个属性值的,所以代码才会一直返回false。
接下来分两种方案给你,一种是修正后的Lodash用法,另一种是更推荐的原生JS方案(毕竟现在不推荐依赖Lodash这类工具库了,原生API已经足够强大)。
方案1:修正Lodash用法(如果还需要用的话)
用Lodash的_.some(检查是否存在至少一个符合条件的元素)或者_.every(检查所有指定值都存在)来实现:
const d = [{ "country": "India", "_id": ObjectId("5ad47b639048dd2367e95d48"), "cities": [] }, { "country": "Spain", "_id": ObjectId("5ad47b639048dd2367e95d49"), "cities": [] }]; const Countries = ['India', 'Spain']; // 需求1:集合中是否包含至少一个指定国家 const hasAnyTargetCountry = _.some(d, item => Countries.includes(item.country)); console.log(hasAnyTargetCountry); // 输出true // 需求2:集合中是否包含所有指定国家 const hasAllTargetCountries = _.every(Countries, country => _.some(d, item => item.country === country)); console.log(hasAllTargetCountries); // 输出true
方案2:原生JS实现(推荐,无需Lodash)
原生数组的some和every方法完全可以替代上面的Lodash功能,而且性能和兼容性都很好:
const d = [{ "country": "India", "_id": ObjectId("5ad47b639048dd2367e95d48"), "cities": [] }, { "country": "Spain", "_id": ObjectId("5ad47b639048dd2367e95d49"), "cities": [] }]; const Countries = ['India', 'Spain']; // 需求1:检查是否存在至少一个指定国家 const hasAnyTargetCountry = d.some(item => Countries.includes(item.country)); console.log(hasAnyTargetCountry); // true // 需求2:检查所有指定国家都存在于集合中 const hasAllTargetCountries = Countries.every(country => d.some(item => item.country === country)); console.log(hasAllTargetCountries); // true
性能优化小技巧(适合大集合)
如果你的集合数据量很大,建议先把集合里的国家名提取成Set,这样查询速度会从O(n)降到O(1):
// 先把集合中的国家名转成Set const existingCountries = new Set(d.map(item => item.country)); // 检查单个国家是否存在 console.log(existingCountries.has('India')); // true // 需求1:是否有至少一个指定国家存在 const hasAnyTargetCountry = Countries.some(country => existingCountries.has(country)); // 需求2:所有指定国家都存在 const hasAllTargetCountries = Countries.every(country => existingCountries.has(country));
内容的提问来源于stack exchange,提问作者Nikhil Savaliya
相关产品推荐
相关产品推荐

