簡體   English   中英

lodash 從

[英]lodash remove object from

我有一個像這樣的 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/

您可以在 forEach 中使用_.remove使用對象作為謂詞:

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

如果為謂詞提供了對象,則創建的 _.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:函數(集合,屬性,值){

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

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

這是使用remove()的示例:

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

假設您的訂單變量名為order ,並且productscomments屬性始終存在。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM