JavaScript中仅使用reduce()判断数组匹配项并执行条件新增操作
实现方案
我们可以将reduce的累加器设计为同时存储两个状态:处理后的结果数组、是否存在目标值的标记,遍历完成后再根据全局标记判断是否追加额外对象,全程仅依赖reduce方法,符合要求。
完整代码
const arr = [{ value: 'test', label: 'Test' }, { value: 'car', label: 'Car' }, ] // 自定义需要校验的目标value const targetValue = 'car' const reduceOutput = arr.reduce((acc, item) => { // 原有逻辑:存入value有效的项 if (item.value) { acc.result.push({ element: item.label, id: item.value, }) } // 匹配到目标值时修改标记 if (item.value === targetValue) { acc.hasMatch = true } return acc }, { result: [], hasMatch: false }) // 遍历完成后统一判断是否追加额外对象 if (!reduceOutput.hasMatch) { reduceOutput.result.push({ element: 'here', id: 'here' }) } const finalRes = reduceOutput.result console.log(finalRes)
效果验证
- 校验目标为
car时:数组存在匹配项,hasMatch为true,不会追加额外对象,最终结果为[{element: 'Test', id: 'test'}, {element: 'Car', id: 'car'}] - 校验目标为
unknown时:数组无匹配项,hasMatch为false,会自动追加{element: 'here', id: 'here'}到结果末尾
逻辑说明
你之前的问题是把判断逻辑写在了遍历的每一轮里,单个元素不匹配就会触发追加,自然会生成多余项。把追加判断放到reduce遍历结束后,基于全局的匹配状态处理,就能实现“整个数组完全不存在目标值才追加”的需求。
内容的提问来源于stack exchange,提问作者Asking
相关产品推荐
相关产品推荐

