如何使用JavaScript移除数组中指定ID及后续的子数据
解决方案
实现思路
- 先遍历数组,找到**目标ID(需转成数字类型)**对应的元素位置
- 若找到该位置,截取数组从起始到该位置的前一个元素的片段;若未找到目标ID,返回原数组的浅拷贝
代码实现
const data = [ {id: 1, name: 'Gill'}, {id: 2, name: 'Gill2'}, {id: 3, name: 'Gill3'}, {id: 4, name: 'Gill4'}, {id: 5, name: 'Gill5'} ]; function filterID(targetId, arr) { // 把字符串类型的目标ID转成数字,和数组里的id类型匹配 const numId = Number(targetId); // 找到目标元素的索引 const targetIndex = arr.findIndex(item => item.id === numId); // 若找到索引,截取0到该索引的部分;没找到则返回原数组的浅拷贝 return targetIndex !== -1 ? arr.slice(0, targetIndex) : [...arr]; } // 调用示例 console.log(filterID("4", data));
运行结果
[ {id: 1, name: 'Gill'}, {id: 2, name: 'Gill2'}, {id: 3, name: 'Gill3'} ]
内容的提问来源于stack exchange,提问作者David
相关产品推荐
相关产品推荐

