JavaScript如何筛选数组中location字段匹配国家和地区条件的对象
JavaScript 多条件筛选数组实现方案
实现思路
直接使用JS数组内置的filter方法遍历数组,对每个对象的location属性同时校验是否包含国家、地区两个关键词即可,可额外加大小写转换逻辑避免大小写不匹配的问题。
完整代码实现
首先定义原始数据:
const cityData = [ { "population": 121321313, "location": "American city in the East" }, { "population": 54646546, "location": "Canadian city in the East" }, { "population": 6546467, "location": "American city in the West" }, { "population": 145313, "location": "American city in the South" }, { "population": 12673, "location": "Canadian city2 in the East" }, { "population": 141313, "location": "Canadian city in the South" }, { "population": 1264473, "location": "Canadian city4 in the East" }, { "population": 12673, "location": "Canadian city6 in the South" } ];
封装筛选函数:
/** * 筛选符合条件的城市 * @param {string} country 国家参数,可选值:American/Canadian * @param {string} region 地区参数,可选值:East/West/South * @returns {Array} 符合条件的城市对象数组 */ function filterCities(country, region) { // 统一转小写,避免大小写导致匹配失败,不需要可删除该逻辑 const formatCountry = country.toLowerCase(); const formatRegion = region.toLowerCase(); return cityData.filter(item => { const formatLocation = item.location.toLowerCase(); return formatLocation.includes(formatCountry) && formatLocation.includes(formatRegion); }) }
测试效果
按照需求筛选东部的加拿大城市:
const result = filterCities('Canadian', 'East'); console.log(result);
输出结果正好是索引为1、4、6的三个对象,符合预期。
严格匹配优化(可选)
如果需要避免关键词部分匹配的异常情况(比如location字段出现CanadianAmerican同时命中两个国家的问题),可以把location按空格拆分成单词数组后再做存在性校验:
function filterCitiesStrict(country, region) { const formatCountry = country.toLowerCase(); const formatRegion = region.toLowerCase(); return cityData.filter(item => { const locationWords = item.location.toLowerCase().split(/\s+/); return locationWords.includes(formatCountry) && locationWords.includes(formatRegion); }) }
内容的提问来源于stack exchange,提问作者user17527939
相关产品推荐
相关产品推荐

