【问题标题】:lodash remove object fromlodash 删除对象
【发布时间】:2016-01-03 06:35:16
【问题描述】:

我有一个这样的 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/

【问题讨论】:

  • 当您说“尝试使用....”时,请向我们展示代码

标签: javascript arrays object lodash


【解决方案1】:

您可以在 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>

【讨论】:

【解决方案2】:

removeObject: 函数(集合、属性、值){

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

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

【讨论】:

    【解决方案3】:

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

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

    假设您的 order 变量名为 order,并且始终存在 products 和 comments 属性。

    【讨论】:

      猜你喜欢
      • 2017-03-12
      • 2018-11-12
      • 2014-07-18
      • 1970-01-01
      • 1970-01-01
      • 2016-11-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多