lodash remove object from

14,795

Solution 1

You can use _.remove inside an forEach using an object as the predicate:

_.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.


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>

Solution 2

removeObject: function(collection,property, value){

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

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

Solution 3

Here's an example using 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.

Share:
14,795
Baumannzone
Author by

Baumannzone

Don't. Click. Here.

Updated on June 17, 2022

Comments

  • Baumannzone
    Baumannzone almost 2 years

    I have a JSON response like this:

    { 
      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?

    Tried using _.remove without success.

    Solution

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

  • Baumannzone
    Baumannzone over 8 years
    Yay! It works really well. I was missing using forEach. Thanks! Demo here: jsfiddle.net/baumannzone/o9yuLuLy
  • Drenmi
    Drenmi over 8 years
    This is the better answer. :-)