Jorge Mejia
Jorge Mejia

Reputation: 1163

Lodash js check if value is different to null

I have a question, is there a method in lodash for validate a key value ?

I have the nex object:

var obj = [
              { name:'A', active:false, quantity : null },
              { name:'B', active:false, quantity : null },
              { name:'C', active:true,  quantity : 4    },
              { name:'D', active:false, quantity : null },
              { name:'E', active:false, quantity : null }
          ];

What i want is, validate if quantity is different to null using a lodash method witout a loop.

Upvotes: 0

Views: 4960

Answers (3)

stasovlas
stasovlas

Reputation: 7416

you can use _.reject with shorthand:

_.reject(obj, { quantity: null })

or using _.isEmpty:

_.reject(obj, o => _.isEmpty(o.quantity))

Upvotes: 0

Thomas
Thomas

Reputation: 103

You can use _.filter to determine this. Try

_.filter(obj, function(o){
        return o.quantity !== null
  }) 

or another method

_.filter(obj, function(o){
     return !o.quantity
})

Upvotes: 2

Kalaiselvan
Kalaiselvan

Reputation: 2134

you can achieve this by using javascript itself

var obj = [
              { name:'A', active:false, quantity : null },
              { name:'B', active:false, quantity : null },
              { name:'C', active:true,  quantity : 4    },
              { name:'D', active:false, quantity : null },
              { name:'E', active:false, quantity : null }
          ];
          
 var predicate=(item)=> item.quantity!=null;         
 var new_obj= obj.filter(predicate);
 console.log(new_obj);

Upvotes: 2

Related Questions