I have a JSON response like this:
{
id_order: '123123asdasd',
products: [
{
description: 'Product 1 description',
ments: [
{
id_ment: 1,
text: 'ment1'
},
{
id_ment: 2,
text: 'ment2'
}
]
}
]
}
How can I remove, with lodash, one object which has an id_ment that is equal to 1, for example?
Tried using _.remove
without success.
Solution
/
I have a JSON response like this:
{
id_order: '123123asdasd',
products: [
{
description: 'Product 1 description',
ments: [
{
id_ment: 1,
text: 'ment1'
},
{
id_ment: 2,
text: 'ment2'
}
]
}
]
}
How can I remove, with lodash, one object which has an id_ment that is equal to 1, for example?
Tried using _.remove
without success.
Solution
https://jsfiddle/baumannzone/o9yuLuLy/
Share Improve this question edited Jan 6, 2021 at 18:52 Jason Aller 3,65228 gold badges41 silver badges39 bronze badges asked Oct 6, 2015 at 11:03 BaumannzoneBaumannzone 7802 gold badges20 silver badges38 bronze badges 1- 4 when you say "tried using...." show us the code – Jamiec Commented Oct 6, 2015 at 11:04
3 Answers
Reset to default 8You can use _.remove inside an forEach using an object as the predicate:
_.forEach(obj.products, function(product) {
_.remove(product.ments, {id_ment: 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',
ments: [{
id_ment: 1,
text: 'ment1'
}, {
id_ment: 2,
text: 'ment2'
}]
}, {
description: 'Product 2 description',
ments: [{
id_ment: 2,
text: 'ment2'
}, {
id_ment: 3,
text: 'ment3'
}]
}, {
description: 'Product 3 description',
ments: [{
id_ment: 1,
text: 'ment1'
}, {
id_ment: 2,
text: 'ment2'
}]
}]
};
_.forEach(obj.products, function(product) {
_.remove(product.ments, {id_ment: 1});
});
document.getElementById('result').innerHTML = JSON.stringify(obj, null, 2);
<script src="https://cdnjs.cloudflare./ajax/libs/lodash.js/3.10.1/lodash.min.js"></script>
<pre id="result"></pre>
removeObject: function(collection,property, value){
return _.reject(collection, function(item){
return item[property] === value;
})
},
Here's an example using remove()
:
_.each(order.products, function (product) {
_.remove(product.ments, function (ment) {
return ment.id_ment === 1;
});
});
Assuming your order variable is named order
, and the products
and ments
properties are always present.