如何使用 lodash 从列表中删除元素? [英] How can I remove an element from a list, with lodash?

查看:66
本文介绍了如何使用 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, "number":32} from the obj对象?

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?

或者是否有一种 javascript 方法可以做到这一点?

Or is there a javascript way to do this?

推荐答案

正如 lyyons 在评论中指出的那样,更惯用和 lodashy 的方法是使用 _.remove,像这样

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

<小时>

或者,您可以通过使用 _.filter 过滤旧数组来创建新数组 并将其分配给同一个对象,就像这样


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

obj.subTopics = _.filter(obj.subTopics, {subTopicId: stToKeep});

这篇关于如何使用 lodash 从列表中删除元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆