【问题标题】:Lodash remove to remove an object from the array based on an id propertyLodash remove 根据 id 属性从数组中删除对象
【发布时间】:2016-08-21 23:15:21
【问题描述】:

我正在查看 remove() 的 lodash 文档,但不知道如何使用它。

假设我有一堆朋友,

[{ friend_id: 3, friend_name: 'Jim' }, { friend_id: 14, friend_name: 'Selma' }]

如何从好友数组中删除friend_id: 14?

【问题讨论】:

    标签: javascript arrays lodash


    【解决方案1】:

    Remove 使用谓词函数。见例子:

    var friends = [{ friend_id: 3, friend_name: 'Jim' }, { friend_id: 14, friend_name: 'Selma' }];
    
    _.remove(friends, friend => friend.friend_id === 14);
    
    console.log(friends); // prints [{"friend_id":3,"friend_name":"Jim"}]
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.js"></script>

    【讨论】:

      【解决方案2】:

      你可以使用过滤器。

      var myArray = [1, 2, 3];
      
      var oneAndThree = _.filter(myArray, function(x) { return x !== 2; });
      
      console.log(allButThisOne); // Should contain 1 and 3.
      

      已编辑:对于您的特定代码,请使用:

      friends = _.filter(friends, function (f) { return f.friend_id !== 14; });
      

      【讨论】:

      • 啊。你怎么知道是使用过滤器还是删除?对不起,如果这是一个非常基本的问题..
      • 这只是个人喜好。对我来说,remove 是愚蠢的,因为它会改变你的数组,PLUS 会返回一个包含已删除值的数组,其中 filter 只返回过滤后的值。
      • 哦,好吧。你认为这有意义吗?我正在像这样使用 lodash 进行 ngrx/store:return assign({}, state, { items: filter(state.items, {id: action.payload.id}) });
      【解决方案3】:

      你也可以这样做

      list.splice(_.findKey(this.list, function(e) {
          return e.id === 12;
      }), 1);
      

      【讨论】:

        猜你喜欢
        • 2020-04-28
        • 2015-12-07
        • 1970-01-01
        • 2012-05-17
        • 1970-01-01
        • 1970-01-01
        • 2013-02-23
        • 1970-01-01
        相关资源
        最近更新 更多