Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
415 views
in Technique[技术] by (71.8m points)

javascript - 如何使用lodash从Array中查找并返回一个对象?(How to use lodash to find and return an object from Array?)

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:(在我的函数中,我正在传递描述以找到匹配的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(我正在尝试使用lodash的find方法: https ://lodash.com/docs#find)

However my variable delete_id is coming out undefined.(但是我的变量delete_id是未定义的。)


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

  ask by Leon Gaban translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

lodash and ES5(lodash和ES5)

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

lodash and ES6(lodash和ES6)

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

docs at https://lodash.com/docs#find(https://lodash.com/docs#find上的文档)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...