190

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/

Leon Gaban
  • 36,509
  • 115
  • 332
  • 529
  • 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 Jan 26 '23 at 07:47

10 Answers10

231

lodash and ES5

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

lodash and ES6

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

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

danday74
  • 52,471
  • 49
  • 232
  • 283
  • 1
    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. – Donniewiko Aug 09 '21 at 11:50
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]);
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • 4
    Thanks! I just found out that this works too `var delete_id = _.result(_.find(savedViews, { 'description': view }), 'id');` Also 10 more mins... – Leon Gaban Jun 25 '15 at 15:07
  • The second solution is wrong, the predicate must be an array to use matchesProperty shorthand: it should be `_.find(savedViews, ['description', view])` – franksands Jul 25 '18 at 14:14
  • 1
    @FranciscoGuimaraes: Well, back in 2015, that's how lodash worked: https://lodash.com/docs/3.10.1#find – Felix Kling Jul 25 '18 at 14:24
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);
Andy
  • 61,948
  • 13
  • 68
  • 95
  • 7
    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 – Leon Gaban Jun 25 '15 at 15:08
  • 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. – kiradotee May 31 '18 at 09:37
  • 4
    @LeonGaban still you can use cleaner without lodash without [0] using ES6 `savedViews.find(el => el.description === view)` – Ram Babu Sep 04 '18 at 20:13
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;
})
Dancrumb
  • 26,597
  • 10
  • 74
  • 130
9

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
xeiton
  • 1,760
  • 16
  • 20
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"}
ABHIJEET KHIRE
  • 2,037
  • 17
  • 10
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.

Ariel
  • 25,995
  • 5
  • 59
  • 69
Afaq Ahmed Khan
  • 2,164
  • 2
  • 29
  • 39
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'});
Bican M. Valeriu
  • 318
  • 3
  • 11
6
var delete_id = _(savedViews).where({ description : view }).get('0.id')
robertklep
  • 198,204
  • 35
  • 394
  • 381
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;
        },