Devesh Agrawal Devesh Agrawal - 5 months ago 24
Javascript Question

How to filter data of an object array with lodash

var brands = [];
brands = [null, {
"id": "1",
"image": "/images/brands/surf_excel.png",
"name": "Surf Excel",
"productCount": "6"
}, {
"id": "2",
"image": "/images/brands/rin.png",
"name": "Rin",
"productCount": "5"
}, {
"id": "3",
"image": "/images/brands/ariel.png",
"name": "Ariel",
"productCount": "4"

Now i want to get the name where id = 3. I tried

var data = _.filter(brands, { 'id': 3 });

But its giving error can't read property of undefined. Assuing there will be only one record for id =3, Can anyne help me on this. How to get name from given id in the above structure.

If there is any better way to get the same result that is also appreciated.


As you have specified and using it's _.filter() method. You can use pass predicate which can a function which will be invoke per iteration. As note it will return you an array.

var data = _.filter(brands, function(brand){
   return brand != null && == 3;

if you want only one element the use _.find()

var data = _.find(brands, function(brand){
   return brand != null && == 3;