admin管理员组

文章数量:1129040

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:

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 :) .21.0/docs/

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/

Share Improve this question edited Jul 18, 2018 at 20:13 Leon Gaban asked Jun 25, 2015 at 15:02 Leon GabanLeon Gaban 39k122 gold badges348 silver badges549 bronze badges 1
  • 1 Thanks for sharing about Ramada. I am just a newbie in the topic of functional programming. Could you elaborate a bit more about why it is more functional programming than lodash.?Thanks. – Uvuvwevwevwe Commented Jan 26, 2023 at 7:47
Add a comment  | 

11 Answers 11

Reset to default 237

lodash and ES5

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

lodash and ES6

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

docs at https://lodash.com/docs#find

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

You can do this easily in vanilla JS:

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

Using filter (original answer):

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

With the find method, your callback is going to be passed the value of each element, like:

{
    description: 'object1', id: 1
}

Thus, you want code like:

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

You don't need Lodash or Ramda or any other extra dependency.

Just use the ES6 find() function in a functional way:

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

Sometimes you need to use 3rd-party libraries to get all the goodies that come with them. However, generally speaking, try avoiding dependencies when you don't need them. Dependencies can:

  • bloat your bundled code size,
  • you will have to keep them up to date,
  • and they can introduce bugs or security risks

Import lodash using

$ npm i --save lodash

var _ = require('lodash'); 

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

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

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

for this find the given Object in an Array, a basic usage example of _.find

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

this would work well

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

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

_.find will help with returning an element in an array, rather than it’s index. So if you have an array of objects and you want to find a single object in the array by a certain key value pare _.find is the right tools for the job.

You can use the following

import { find } from 'lodash'

Then to return the entire object (not only its key or value) from the list with the following:

let match = find(savedViews, { 'ID': 'id to match'});
var delete_id = _(savedViews).where({ description : view }).get('0.id')

Fetch id basing on name

 {
    "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;
        },
const _ = require("lodash");

// Using _.matches() method
let geek = [{ 'java': 3, 'python': 5, 'js': 7 },
{ 'java': 4, 'python': 2, 'js': 6 }
];

let gfg = _.filter(geek, _.matches({ 'java': 3, 'js': 7 }));

// Storing the Result
console.log(gfg);

https://www.geeksforgeeks.org/lodash-_-matches-method/

本文标签: javascriptHow to use lodash to find and return an object from ArrayStack Overflow