我试图使用LoDash从数组中删除对象。
var roomList = [
{id: '12345', room: 'kitchen'},
{id: '23456', room: 'lounge'},
{id: '34567', room: 'bathroom'},
];
console.log(roomList); //outputs all 3 rooms
_.pull(roomList, {id: '12345'});
console.log(roomList); //STILL outputs all 3 rooms!
我认为_pull
可以在这种情况下发挥作用,但事实并非如此。如何使用LoDash从数组中删除对象?
答案 0 :(得分:4)
您可以使用_.remove:
_.remove(roomList, {id: '12345'});
答案 1 :(得分:1)
试试这段代码:
var roomList = [
{id: '12345', room: 'kitchen'},
{id: '23456', room: 'lounge'},
{id: '34567', room: 'bathroom'},
];
console.log(roomList);
_.pull(roomList, _.find(roomList, {id: '12345'}));
console.log(roomList);
答案 2 :(得分:0)
另一种方法是使用_.filter
;
roomList = _.filter(roomList, function(item) {return item.id != '12345'});
console.log(roomList);