[英]filter an object with condition using Underscore.js
I am using Underscore.js library in my application. 我在我的应用程序中使用Underscore.js库。 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 我想将此对象压缩为仅具有不具有“ no”属性的属性,这应导致以下对象
{a:"1", b:"2", c: "3"}
In Uderscore.js, I used the below code 在Uderscore.js中,我使用了以下代码
_.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. 但是在上面的代码中,我需要一个函数来输出
no
包含no
值的键,而不是'attr'。 Is there a better way to do this. 有一个更好的方法吗。 Please let me know how to get the keys having 'no' values.
请让我知道如何获取具有“ no”值的键。
You can use the _.omit
as 您可以使用
_.omit
作为
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: 下划线的
_.omit()
也接受一个“谓词”,这是它们与_.filter()
相似的函数的术语:
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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.