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

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

问题描述

我的对象:

<预><代码>[{描述:'object1',id:1},{描述:'object2',id:2}{描述:'object3',id:3}{描述:'object4',id:4}]

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

function pluckSavedView(action, view) {console.log('动作:', 动作);console.log('pluckSavedView: ', view);//视图 = 'object1'var savedViews = retrieveSavedViews();console.log('savedViews:', savedViews);如果(动作 === '删除'){var delete_id = _.result(_.find(savedViews, function(description) {返回描述 === 查看;}), 'ID');console.log('delete_id: ', delete_id);//应该是'1',但未定义}}

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

但是我的变量 delete_id 未定义.

<小时>

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

解决方案

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

var delete_id = _.result(_.find(savedViews, function(obj) {返回 obj.description === 视图;}), 'ID');

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

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

Lodash v4:

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

My objects:

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

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

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

However my variable delete_id is coming out undefined.


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/

解决方案

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

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

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

Lodash v4:

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

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

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