使用lodash从数组中删除数组中的元素

时间:2015-05-22 11:47:21

标签: javascript arrays lodash

我想使用lodash根据removeUser数组中的userName值删除removeUser数组中的用户。这是我的输入数据:

{"users":[
{"title":"Mr", "firstName":"John", "lastName":"Doe", "email":"jdoe@google.com", "userName" : "jdoe", "groups": [{"name": "Manager"}]},
{"title":"Ms", "firstName":"Anna", "lastName":"Smith","email":"asmith@google.com", "userName" : "asmith", "groups": [{"name": "Administrator"}, {"name": "Manager"}]},
{"title":"Mr", "firstName":"Peter", "lastName":"Jones", "email":"pjones@google.com", "userName" : "pjones", "groups": [{"name": "Administrator"}, {"name": "Manager"}]},
{"title":"Ms", "firstName":"Jenny", "lastName":"Otter","email":"jotter@google.com", "userName" : "jotter", "groups": [{"name": "Administrator"}, {"name": "Manager"}]}
]}

var removeUser = ['jdoe', 'asmith'];  //usernames of users to be removed

这就是我所拥有的,但我需要一个foreach循环:

_remove(users, { userName: [removeUser]})

这样我最终会得到一个更新的users数组:

{"users":[
{"title":"Mr", "firstName":"Peter", "lastName":"Jones", "email":"pjones@google.com", "userName" : "pjones", "groups": [{"name": "Administrator"}, {"name": "Manager"}]},
{"title":"Ms", "firstName":"Jenny", "lastName":"Otter","email":"jotter@google.com", "userName" : "jotter", "groups": [{"name": "Administrator"}, {"name": "Manager"}]}
]}

1 个答案:

答案 0 :(得分:1)

你可以使用callback as second argument,就像这样



var data = {"users": [
  {"title":"Mr", "firstName":"John", "lastName":"Doe", "email":"jdoe@google.com", "userName" : "jdoe", "groups": [{"name": "Manager"}]},
  {"title":"Ms", "firstName":"Anna", "lastName":"Smith","email":"asmith@google.com", "userName" : "asmith", "groups": [{"name": "Administrator"}, {"name": "Manager"}]},
  {"title":"Mr", "firstName":"Peter", "lastName":"Jones", "email":"pjones@google.com", "userName" : "pjones", "groups": [{"name": "Administrator"}, {"name": "Manager"}]},
  {"title":"Ms", "firstName":"Jenny", "lastName":"Otter","email":"jotter@google.com", "userName" : "jotter", "groups": [{"name": "Administrator"}, {"name": "Manager"}]}
]};

var removeUser = ['jdoe', 'asmith']; 

_.remove(data.users, function(el) {
  // if el.userName exists in removeUser return true and remove it from data.users
  return removeUser.indexOf(el.userName) >= 0;
});

console.log(data);

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.9.0/lodash.js"></script>
&#13;
&#13;
&#13;