lodash从中删除对象 [英] lodash remove object from
本文介绍了lodash从中删除对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这样的JSON响应:
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'
}
]
}
]
}
如何使用 lodash 删除一个具有 id_comment 的对象例如等于1?
How can I remove, with lodash, one object which has an id_comment that is equal to 1, for example?
尝试使用 _ .. remove
失败.
https://jsfiddle.net/baumannzone/o9yuLuLy/
推荐答案
您可以使用 _.remove 在forEach中使用一个对象作为谓词:
You can use _.remove inside an forEach using an object as the predicate:
_.forEach(obj.products, function(product) {
_.remove(product.comments, {id_comment: 1});
});
如果为谓词提供了一个对象,则创建的_.matches样式回调对于具有给定对象属性的元素返回true,否则返回false.
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>
这篇关于lodash从中删除对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文