如何使用lodash从Array中查找并返回一个对象? [英] How to use lodash to find and return an object from Array?

查看:978
本文介绍了如何使用lodash从Array中查找并返回一个对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的对象:

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

在我的函数中,我在描述中传递以找到匹配的ID:

In my function below I'm passing in the description to find the matching 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

I'm trying to use lodash's find method: https://lodash.com/docs#find

但我的变量 delete_id 未定义。

更新让人们检查这个问题,Ramda是一个很好的库,可以做同样的事情lodash,但是在更多功能的编程方式:)
http://ramdajs.com/0.21.0/docs/

Update for people checking this question out, Ramda is a nice library to do the same thing lodash does, but in a more functional programming way :) http://ramdajs.com/0.21.0/docs/

推荐答案

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

The argument passed to the callback is one of the elements of the array. The elements of your array are objects of the form {description: ..., id: ...}.

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

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

Yet another alternative from the docs you linked to (lodash v3):

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

Lodash v4:

Lodash v4:

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

这篇关于如何使用lodash从Array中查找并返回一个对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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