本文介绍了我怎样才能从列表中删除一个元素,lodash?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象,看起来像这样:

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;

我在其他的东西应用_lodash使用。有没有办法使用_lodash删除条目的有效途径: {subTopicId:2,数字:32} OBJ 对象或者是有一个javascript办法做到这一点?

I have _lodash used 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?

推荐答案

由于lyyons在评论中指出,更地道和lodashy办法做到这一点是使用的,像这样

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
});

除此之外,可以传递predicate函数,其结果将被用于确定是否当前元素已被删除或不

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;
});

这篇关于我怎样才能从列表中删除一个元素,lodash?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 05:32