JS按条件删除数组中首个total属性为0的对象元素
需求说明
现有如下结构的对象数组:
[ { year: 2023, total: 0, transfer: -13, totalWithTransfer: -13, takenHolidays: 0, result: 24, vacationAfterToday: 0, vacationBeforeToday: 0 }, { year: 2022, total: 0, transfer: -4, totalWithTransfer: -4, takenHolidays: 9, result: 27, vacationAfterToday: 3, vacationBeforeToday: 6 }, { year: 2021, total: 0, transfer: 0, totalWithTransfer: 0, takenHolidays: 4, result: 28, vacationAfterToday: 0, vacationBeforeToday: 4 }, { year: 2020, total: 0, transfer: 0, totalWithTransfer: 0, takenHolidays: 0, result: 24, vacationAfterToday: 0, vacationBeforeToday: 0 } ]
需要实现逻辑:检查数组第一个对象的total属性值是否为0,若结果为0,则将该对象从数组中移除。
实现代码
根据是否需要保留原数组,有两种常用实现方式:
- 直接修改原数组(性能更好,适合不需要保留原始数据的场景)
// 数组存储在vacationList变量中,可根据你的实际变量名替换 if (vacationList.length && vacationList[0].total === 0) { vacationList.shift(); }
逻辑说明:先判断数组非空避免索引越界,用严格等于===判断属性值避免隐式类型转换导致的误判,符合条件时调用shift()方法删除数组第一个元素,该方法会直接在原数组上生效。
- 不修改原数组,返回新数组(适合需要保留原始数据的不可变数据场景)
const processedList = vacationList.length && vacationList[0].total === 0 ? vacationList.slice(1) : [...vacationList];
逻辑说明:符合删除条件时调用slice(1)返回从索引1开始到数组末尾的新数组,不符合条件时通过展开运算符拷贝原数组返回,全程不会改动原始数组。
针对给出的示例数据,第一个元素year:2023的对象total值为0,执行上述逻辑后会被正常移除,处理后数组的第一个元素为2022年对应的记录。
内容的提问来源于stack exchange,提问作者user18460597
相关产品推荐
相关产品推荐

