简体   繁体   English

lodash 从

[英]lodash remove object from

I have a JSON response like this:我有一个像这样的 JSON 响应:

{ 
  id_order: '123123asdasd',
  products: [ 
    { 
      description: 'Product 1 description',
      comments: [
        { 
          id_comment: 1,
          text: 'comment1'
        },
        { 
          id_comment: 2,
          text: 'comment2'
        }
      ] 
    }
  ]
}

How can I remove, with lodash , one object which has an id_comment that is equal to 1, for example?例如,如何使用lodash删除一个id_comment等于 1 的对象?

Tried using _.remove without success.尝试使用_.remove没有成功。

Solution解决方案

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

You can use _.remove inside an forEach using an object as the predicate:您可以在 forEach 中使用_.remove使用对象作为谓词:

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

If an object is provided for predicate the created _.matches style callback returns true for elements that have the properties of the given object, else false.如果为谓词提供了对象,则创建的 _.matches 样式回调对于具有给定对象属性的元素返回 true,否则返回 false。


 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>

removeObject: function(collection,property, value){ removeObject:函数(集合,属性,值){

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

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

Here's an example using remove() :这是使用remove()的示例:

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

Assuming your order variable is named order , and the products and comments properties are always present.假设您的订单变量名为order ,并且productscomments属性始终存在。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM