TypeScript中筛选混合元素数组并提取狗项圈标签后四位的最优方法
最优实现方案:filter + map 组合
对于你的需求,用filter配合map是最优解——逻辑拆分清晰,代码可读性强,特别适合TypeScript新手理解和维护。
步骤说明
- 先用
filter从混合数组中筛选出所有包含dog属性的项; - 再用
map转换每个狗的对象,提取需要的字段,并截取collarTag的后四位。
完整TypeScript代码
// 定义类型(TS里加类型能避免很多类型报错,新手也能更清楚数据结构) type Dog = { name: string; breed: string; collarTag: string; }; type Snake = { name: string; species: string; }; type AnimalItem = { dog: Dog } | { snake: Snake }; type AnimalsData = { animals: AnimalItem[] }; // 原始数据 const data: AnimalsData = { "animals": [ { "dog": { "name": "Buster", "breed": "Poodle", "collarTag": "ABCDEF9999" } }, { "snake": { "name": "Sammy", "species": "Copperhead" } }, { "dog": { "name": "Rex", "breed": "Mixed", "collarTag": "ABCDEF1234" } } ] }; // 核心处理逻辑 const result = data.animals // 筛选出所有狗的项 .filter(item => 'dog' in item) // 转换结构,提取collarTag后四位 .map(item => { const { name, breed, collarTag } = item.dog; return { name, breed, collarLastFour: collarTag.slice(-4) // 截取字符串最后四位 }; }); console.log(result);
输出结果
[ { name: 'Buster', breed: 'Poodle', collarLastFour: '9999' }, { name: 'Rex', breed: 'Mixed', collarLastFour: '1234' } ]
为什么不推荐用reduce?
reduce也能一次性完成筛选和转换,但逻辑会揉在一起,代码可读性差,新手容易搞混累加器的逻辑。除非你需要在遍历过程中做更复杂的多步骤操作,否则没必要用它。
补充:reduce实现方式(仅作参考)
const result = data.animals.reduce((acc, item) => { if ('dog' in item) { const { name, breed, collarTag } = item.dog; acc.push({ name, breed, collarLastFour: collarTag.slice(-4) }); } return acc; }, [] as { name: string; breed: string; collarLastFour: string }[]);
内容的提问来源于stack exchange,提问作者Colema18
相关产品推荐
相关产品推荐

