[javascript] How to use lodash to find and return an object from Array?

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/

This question is related to javascript arrays lodash

The answer is


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.


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

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

You can do this easily in vanilla JS:

Using find

_x000D_
_x000D_
const savedViews = [{"description":"object1","id":1},{"description":"object2","id":2},{"description":"object3","id":3},{"description":"object4","id":4}];_x000D_
_x000D_
const view = 'object2';_x000D_
_x000D_
const delete_id = savedViews.find(obj => {_x000D_
  return obj.description === view;_x000D_
}).id;_x000D_
_x000D_
console.log(delete_id);
_x000D_
_x000D_
_x000D_

Using filter (original answer)

_x000D_
_x000D_
const savedViews = [{"description":"object1","id":1},{"description":"object2","id":2},{"description":"object3","id":3},{"description":"object4","id":4}];_x000D_
_x000D_
const view = 'object2';_x000D_
_x000D_
const delete_id = savedViews.filter(function (el) {_x000D_
  return el.description === view;_x000D_
})[0].id;_x000D_
_x000D_
console.log(delete_id);
_x000D_
_x000D_
_x000D_


lodash and ES5

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

lodash and ES6

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

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


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

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

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

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

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?

Examples related to lodash

Can't perform a React state update on an unmounted component Angular 4 HttpClient Query Parameters use Lodash to sort array of object by value How to group an array of objects by key Removing object properties with Lodash How to merge two arrays of objects by ID using lodash? Error: EACCES: permission denied Replacing objects in array lodash: mapping array to object Correct way to import lodash