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

2020/11/10 06:22 · javascript ·  · 0评论

我的对象:

[
    {
        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/

传递给回调的参数是数组的元素之一。数组的元素是形式的对象{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]);

lodash和ES5

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

lodash和ES6

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

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

您可以在香草JS中轻松完成此操作:

使用 find

const savedViews = [{"description":"object1","id":1},{"description":"object2","id":2},{"description":"object3","id":3},{"description":"object4","id":4}];

const view = 'object2';

const delete_id = savedViews.find(obj => {
  return obj.description === view;
}).id;

console.log(delete_id);

使用filter(原始答案)

const savedViews = [{"description":"object1","id":1},{"description":"object2","id":2},{"description":"object3","id":3},{"description":"object4","id":4}];

const view = 'object2';

const delete_id = savedViews.filter(function (el) {
  return el.description === view;
})[0].id;

console.log(delete_id);

使用该find方法,您的回调将被传递每个元素的值,例如:

{
    description: 'object1', id: 1
}

因此,您需要如下代码:

_.find(savedViews, function(o) {
        return o.description === view;
})

您不需要Lodash或Ramda或任何其他额外的依赖项。

只需以功能性方式使用ES6 find()函数:

savedViews.find(el => el.description === view)

有时,您需要使用3rd-party库来获取它们附带的所有好东西。但是,通常来说,在不需要依赖尽量避免依赖依赖项可以:

  • your肿您捆绑的代码大小,
  • 您将必须使它们保持最新状态,
  • 他们可能会引入错误或安全风险

为此,在数组中找到给定的对象,_.find的基本用法示例

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

这会很好

q = _.find(array, {id:'4'}); // delete id

console.log(q); // {description: 'object4', id: 4}

_.find有助于返回数组中的元素,而不是索引。因此,如果您有一个对象数组,并且希望通过某个键值对在数组中找到单个对象,则_.find是完成此任务的正确工具。

var delete_id = _(savedViews).where({ description : view }).get('0.id')

您可以使用以下内容

import { find } from 'lodash'

然后使用以下命令从列表中返回整个对象(不仅是其键或值):

let match = find(savedViews, { 'ID': 'id to match'});

导入lodash使用

$ npm i-保存lodash

var _ = require('lodash'); 

var objArrayList = 
    [
         { name: "user1"},
         { name: "user2"}, 
         { name: "user2"}
    ];

var Obj = _.find(objArrayList, { name: "user2" });

// Obj ==> { name: "user2"}

根据名称获取ID

 {
    "roles": [
     {
      "id": 1,
      "name": "admin",
     },
     {
      "id": 3,
      "name": "manager",
     }
    ]
    }



    fetchIdBasingOnRole() {
          const self = this;
          if (this.employee.roles) {
            var roleid = _.result(
              _.find(this.getRoles, function(obj) {
                return obj.name === self.employee.roles;
              }),
              "id"
            );
          }
          return roleid;
        },
本文地址:http://javascript.askforanswer.com/ruheshiyonglodashcongarraychazhaobingfanhuiduixiang.html
文章标签: ,   ,  
版权声明:本文为原创文章,版权归 javascript 所有,欢迎分享本文,转载请保留出处!

文件下载

老薛主机终身7折优惠码boke112

上一篇:
下一篇:

评论已关闭!