Lodash 如何从对象中移除元素?

3
我有一个像这样的JSON响应:
{ 
  id_order: '123123asdasd',
  products: [ 
    { 
      description: 'Product 1 description',
      comments: [
        { 
          id_comment: 1,
          text: 'comment1'
        },
        { 
          id_comment: 2,
          text: 'comment2'
        }
      ] 
    }
  ]
}

如何使用lodash从一个对象中删除id_comment等于1的对象?
尝试使用_.remove失败了。
解决方案:

https://jsfiddle.net/baumannzone/o9yuLuLy/


4
当您说“尝试使用……”时,请展示给我们代码。 - Jamiec
3个回答

8

您可以在使用对象作为谓词的forEach中使用_.remove

_.forEach(obj.products, function(product) {
  _.remove(product.comments, {id_comment: 1});
});

如果为predicate提供了一个对象,那么创建的_.matches风格回调函数将返回具有给定对象属性的元素的真值,否则返回假值。

var obj = {
  id_order: '123123asdasd',
  products: [{
    description: 'Product 1 description',
    comments: [{
      id_comment: 1,
      text: 'comment1'
    }, {
      id_comment: 2,
      text: 'comment2'
    }]
  }, {
    description: 'Product 2 description',
    comments: [{
      id_comment: 2,
      text: 'comment2'
    }, {
      id_comment: 3,
      text: 'comment3'
    }]
  }, {
    description: 'Product 3 description',
    comments: [{
      id_comment: 1,
      text: 'comment1'
    }, {
      id_comment: 2,
      text: 'comment2'
    }]
  }]
};

_.forEach(obj.products, function(product) {
  _.remove(product.comments, {id_comment: 1});
});

document.getElementById('result').innerHTML = JSON.stringify(obj, null, 2);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.1/lodash.min.js"></script>
<pre id="result"></pre>


太棒了!它运行得非常顺利。我以前一直忘记使用forEach。谢谢! 在这里查看演示:https://jsfiddle.net/baumannzone/o9yuLuLy/ - Baumannzone
1
这是更好的答案。 :-) - Drenmi

2

removeObject: function(collection, property, value) {

// 从集合中移除指定属性和值的对象

     return   _.reject(collection, function(item){

        return item[property] === value;
    })
},

1
这是一个使用remove()的示例:

_.each(order.products, function (product) {
    _.remove(product.comments, function (comment) {
        return comment.id_comment === 1;
    });
});

假设您的订单变量名为order,且productscomments属性始终存在。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接