195

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/

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. Commented Jan 26, 2023 at 7:47

11 Answers 11

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

Sign up to request clarification or add additional context in comments.

1 Comment

When passing a variable in the find method, make sure to name the variable the same as the property name. In my case, i was looking for a country in my countryList. The country object has the properties code and name. When i did const countryName = "Netherlands"; let country = _.find(countryList, {countryName}); undefined was returned. When i used const name = "Netherlands"; let country = _.find(countryList, {name}); the correct object was returned.
191

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

3 Comments

Thanks! I just found out that this works too var delete_id = _.result(_.find(savedViews, { 'description': view }), 'id'); Also 10 more mins...
The second solution is wrong, the predicate must be an array to use matchesProperty shorthand: it should be _.find(savedViews, ['description', view])
@FranciscoGuimaraes: Well, back in 2015, that's how lodash worked: lodash.com/docs/3.10.1#find
43

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

3 Comments

True, but lodash seems so much cleaner, I don't have to use [0] this is the solution I'm going with var delete_id = _.result(_.find(savedViews, { 'description': view }), 'id'); Thanks for the demo tho +1
Isn't it going to fail when you force [0] out an empty result? So +1 to @LeonGaban that Lodash should handle that by default.
@LeonGaban still you can use cleaner without lodash without [0] using ES6 savedViews.find(el => el.description === view)
15

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

Comments

10

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

Comments

9

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

1 Comment

add more details
8

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.

Comments

7

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

Comments

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

Comments

1

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

Comments

1
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/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.