javascript lodash 从
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32968335/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
lodash remove object from
提问by Baumannzone
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 wich id_commentis equal to 1, for example?
例如,如何使用lodash删除一个id_comment等于 1 的对象?
Tried using _.remove
without success. Any help?
尝试使用_.remove
没有成功。有什么帮助吗?
Cheers.
干杯。
Solution
解决方案
回答by DTing
You can use _.removeinside 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>
回答by Davet
removeObject: function(collection,property, value){
removeObject:函数(集合,属性,值){
return _.reject(collection, function(item){
return item[property] === value;
})
},
回答by Drenmi
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
,并且products
和comments
属性始终存在。