如何在JavaScript中按statecode和citydescription过滤嵌套对象数组?
按州编码和城市描述过滤数据
我有一个包含城市和州信息的对象数组,需要依据statecode和citydescription属性进行过滤。数据结构如下:
{ "stateProvinces": [ { "cities": [ { "code": "T001", "citydescription": "Chennai" }, // ... 其他城市 ], "statecode": "TN" }, // ... 其他州 ] }
需求:当传入州编码TN和城市描述Chennai时,期望输出:Code: T001。
我已经实现了按州过滤的代码:
const filtervalue = getCityNames.filter((code) => { return code.statecode == "TN"; });
完善后的过滤逻辑
因为statecode通常是唯一标识,用find替代filter效率更高(找到匹配项后立即停止遍历),之后再在该州的城市列表中匹配目标城市:
// 定义目标过滤条件 const targetStateCode = "TN"; const targetCityDesc = "Chennai"; // 第一步:找到匹配的州 const targetState = getCityNames.find(state => state.statecode === targetStateCode); if (targetState) { // 第二步:在该州的城市列表中找到匹配的城市 const targetCity = targetState.cities.find(city => city.citydescription === targetCityDesc); if (targetCity) { console.log(`Code: ${targetCity.code}`); // 输出:Code: T001 } else { console.log("未找到指定城市"); } } else { console.log("未找到指定州"); }
如果需要处理多个州匹配的场景(比如存在重复statecode的情况),可以用flatMap展开所有匹配州的城市,再统一过滤:
const targetCities = getCityNames .filter(state => state.statecode === targetStateCode) .flatMap(state => state.cities) .filter(city => city.citydescription === targetCityDesc); // 遍历输出所有匹配的城市编码 targetCities.forEach(city => console.log(`Code: ${city.code}`));
内容的提问来源于stack exchange,提问作者Nishanth
相关产品推荐
相关产品推荐

