简体   繁体   中英

filter an object with condition using Underscore.js

I am using Underscore.js library in my application. I have an Object

{a:"1", b:"2", c: "3", d:"no", e: "no"}

I want to condense this object to have only the properties not having "no" attribute which should result in the below object

    {a:"1", b:"2", c: "3"}

In Uderscore.js, I used the below code

_.omit(obj, 'attr');

But in the above code, instead of the 'attr', I need to have a function which will output the keys containing no values. Is there a better way to do this. Please let me know how to get the keys having 'no' values.

You can use the _.omit as

var obj = {a:"1", b:"2", c: "3", d:"no", e: "no"};
// _.omit returns a copy of the object
obj = _.omit(obj, function(value, key, object) {
  return (value == "no");
});
console.log(obj);

Underscore's _.omit() also accepts a 'predicate', which is their terminology for a function similar to _.filter() 's:

 var o = {a:"1", b:"2", c: "3", d:"no", e: "no"} console.log(_.omit(o, function(v){ return v === 'no'; })); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM