如何使用 lodash 从 Array 查找并返回对象?

2022-08-30 01:50:42

我的对象:

[
    {
        description: 'object1', id: 1
    },
    {
        description: 'object2', id: 2
    }
    {
        description: 'object3', id: 3
    }
    {
        description: 'object4', id: 4
    }
]

在下面的函数中,我传入描述以查找匹配的ID:

function pluckSavedView(action, view) {
    console.log('action: ', action);
    console.log('pluckSavedView: ', view);  // view = 'object1'

    var savedViews = retrieveSavedViews();
    console.log('savedViews: ', savedViews);

    if (action === 'delete') {
        var delete_id = _.result(_.find(savedViews, function(description) {
            return description === view;
        }), 'id');

        console.log('delete_id: ', delete_id); // should be '1', but is undefined
    }
}

我正在尝试使用lodash的find方法:https://lodash.com/docs#find

但是,我的变量未定义。delete_id


对于检查这个问题的人来说,Ramda是一个很好的库,可以做lodash所做的同样的事情,但是以一种更实用的编程方式:)http://ramdajs.com/0.21.0/docs/


答案 1

洛达什和ES5

var song = _.find(songs, {id:id});

洛达什和ES6

let song = _.find(songs, {id});

https://lodash.com/docs#find 的文档


答案 2

传递给回调的参数是数组的元素之一。数组的元素是 形式的对象。{description: ..., id: ...}

var delete_id = _.result(_.find(savedViews, function(obj) {
    return obj.description === view;
}), 'id');

您链接到的文档(lodash v3)的另一种选择:

_.find(savedViews, 'description', view);

Lodash v4:

_.find(savedViews, ['description', view]);