删除数组中的指定数据除了用Lodash遍历删除指定数组中的数据这种方法,还可以使用原生的filter
和Lodash的_.filter
。下面来看看例子,我们仍人删除id
为3
、4
的数据。
// 原始数据
const data = [{
"id": 1,
"title": "\u9505\u5305\u8089",
"current_price": "52",
"price": "68",
"pic": "https:\/\/img1.baidu.com\/it\/u=2023055444,1293178019&fm=26&fmt=auto&gp=0.jpg"
}, {
"id": 2,
"title": "\u6e9c\u8089\u6bb5",
"current_price": "51",
"price": "67",
"pic": "https:\/\/img1.baidu.com\/it\/u=3204271464,2328819560&fm=26&fmt=auto&gp=0.jpg"
}, {
"id": 3,
"title": "\u9171\u9aa8\u5934",
"current_price": "50",
"price": "60",
"pic": "https:\/\/img1.baidu.com\/it\/u=479160956,3975263943&fm=26&fmt=auto&gp=0.jpg"
}, {
"id": 4,
"title": "\u70e4\u51b7\u9762",
"current_price": "10",
"price": "13",
"pic": "https:\/\/img1.baidu.com\/it\/u=3124547070,2003217950&fm=26&fmt=auto&gp=0.jpg"
}, {
"id": 5,
"title": "\u70e4\u9c7f\u9c7c",
"current_price": "5",
"price": "8",
"pic": "https:\/\/img2.baidu.com\/it\/u=269395686,4199110830&fm=26&fmt=auto&gp=0.jpg"
}, {
"id": 6,
"title": "\u70e4\u5b9e\u86cb",
"current_price": "2",
"price": "3",
"pic": "https:\/\/img0.baidu.com\/it\/u=285168336,1592951661&fm=26&fmt=auto&gp=0.jpg"
}, {
"id": 7,
"title": "\u7cd6\u846b\u82a6",
"current_price": "2",
"price": "3.5",
"pic": "https:\/\/img2.baidu.com\/it\/u=2751411262,1347874489&fm=26&fmt=auto&gp=0.jpg"
}, {
"id": 8,
"title": "\u7092\u9178\u5976",
"current_price": "8.5",
"price": "14",
"pic": "https:\/\/img1.baidu.com\/it\/u=1571261545,3991125646&fm=26&fmt=auto&gp=0.jpg"
}, {
"id": 9,
"title": "\u70b8\u51b7\u9762",
"current_price": "10",
"price": "15",
"pic": "https:\/\/img2.baidu.com\/it\/u=2628349012,2260513904&fm=26&fmt=auto&gp=0.jpg"
}, {
"id": 10,
"title": "\u51bb\u8c46\u8150",
"current_price": "5",
"price": "8",
"pic": "https:\/\/img0.baidu.com\/it\/u=2910047582,2840012354&fm=26&fmt=auto&gp=0.jpg"
}, {
"id": 11,
"title": "\u7f8a\u874e\u5b50",
"current_price": "66",
"price": "98",
"pic": "https:\/\/img1.baidu.com\/it\/u=1298983180,3628968793&fm=26&fmt=auto&gp=0.jpg"
}]
// 需要删除的id数组
const IDs = [3, 4]
// Lodash _.filter
const arr1 = _.filter(data, function(o) { return !IDs.includes(o.id) ; });
console.log(arr1);
// 原生 filter
const arr2 = data.filter(item => !IDs.includes(item.id) )
console.log(arr2);
// 原始数据 data 未改变
console.log(data);
这里需要注意的是原始数据 data
未改变,之前遍历方法,是直接改变了data
。