I have an object that looks like this:
var obj = {
"objectiveDetailId": 285,
"objectiveId": 29,
"number": 1,
"text": "x",
"subTopics": [{
"subTopicId": 1,
"number": 1
}, {
"subTopicId": 2,
"number": 32
}, {
"subTopicId": 3,
"number": 22
}]
}
var stToDelete = 2;
I have lodash installed in my application for other things. Is there an efficient way to use lodash to delete the entry: {"subTopicId":2, "number":32} from the obj object?
Or is there a javascript way to do this?
As lyyons pointed out in the comments, more idiomatic and lodashy way to do this would be to use _.remove, like this
_.remove(obj.subTopics, {
subTopicId: stToDelete
});
Apart from that, you can pass a predicate function whose result will be used to determine if the current element has to be removed or not.
_.remove(obj.subTopics, function(currentObject) {
return currentObject.subTopicId === stToDelete;
});
Alternatively, you can create a new array by filtering the old one with _.filter and assign it to the same object, like this
obj.subTopics = _.filter(obj.subTopics, function(currentObject) {
return currentObject.subTopicId === stToDelete;
});
Or
obj.subTopics = _.filter(obj.subTopics, {subTopicId: stToDelete});
you can do it with _pull.
_.pull(obj["subTopics"] , {"subTopicId":2, "number":32});
check the reference
You can now use _.reject which allows you to filter based on what you need to get rid of, instead of what you need to keep.
unlike _.pull or _.remove that only work on arrays, ._reject is working on any Collection
obj.subTopics = _.reject(obj.subTopics, (o) => {
return o.number >= 32;
});
In Addition to @thefourtheye answer, using predicate instead of traditional anonymous functions:
_.remove(obj.subTopics, (currentObject) => {
return currentObject.subTopicId === stToDelete;
});
OR
obj.subTopics = _.filter(obj.subTopics, (currentObject) => {
return currentObject.subTopicId === stToDelete;
});
lodash and typescript
const clearSubTopics = _.filter(obj.subTopics, topic => (!_.isEqual(topic.subTopicId, 2)));
console.log(clearSubTopics);
Here is the simple lodash function with array and deleting it with the index number.
index_tobe_delete = 1
fruit = [{a: "apple"}, {b: "banana"}, {c: "choco"}]
_.filter(fruit, (value, key)=> {
return (key !== index_tobe_delete)
})
来源:https://stackoverflow.com/questions/21281286/how-can-i-remove-an-element-from-a-list-with-lodash