有这么一个数组
let arr = [
{id:1,value:2},
{id:2,value:3},
.......
]
想删除数组里id=8的元素,
使用es6如何方便快捷的实现
有这么一个数组
let arr = [
{id:1,value:2},
{id:2,value:3},
.......
]
想删除数组里id=8的元素,
使用es6如何方便快捷的实现
let arr = [
{id:1,value:2},
{id:2,value:3},
{id:8,value:9}
]
const newArr = arr.filter(obj=>obj.id!==8)
const arr = [{ id: 1 }, { id: 8 }]
const index = arr.findIndex(item => item.id === 8)
index > -1 && arr.splice(index, 1)
我来抛砖引玉吧~~
有个思路是按id的值作为数组的序号来进行存储,如arr[8] = {id:8,value:8};
然后你要置空时直接arr[8] = undefined即可;
拿数组时走下filter即可,arr2 = arr1.filter(item => item)。
let arr = [
{id:1,value:2},
{id:2,value:3},
{id:3,value:3},
{id:4,value:3},
{id:5,value:3},
{id:6,value:3},
{id:7,value:3},
{id:6,value:3}
]
var myarr = arr.filter(function(s){
if(s.id==8){
return false;
}else{
return s;
}
}) ;
console.log(myarr);
用lodash
import _ from lodash;
var array = [1, 2, 3, 4];
var evens = _.remove(array, function(n) {
return n % 2 == 0;
});
console.log(array);
// => [1, 3]
console.log(evens);
// => [2, 4]
let arr = [
{id:1,value:1},
{id:2,value:2},
{id:3,value:3},
{id:4,value:4},
{id:5,value:5},
{id:6,value:6},
{id:7,value:7},
{id:8,value:8}
]
console.log(arr.filter(s=>{return s.id===8?false:s}));
2 回答1.6k 阅读✓ 已解决
2 回答908 阅读✓ 已解决
1 回答844 阅读✓ 已解决
557 阅读
137 阅读
ES6 findIndex
MDN :Array.prototype.findIndex()findIndex()
方法返回数组中满足提供的测试函数的第一个元素的索引。否则返回-1。推荐文章:【深度长文】JavaScript数组所有API全解密 | louis blog