如何使用 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/