Javascript 使用下划线检查对象数组是否具有键值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10698340/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check if an array of objects have a key value using underscore
提问by underscore666
How can check if an array of objects have a key value using underscore.
如何使用下划线检查对象数组是否具有键值。
Example:
例子:
var objects = [
{id:1, name:'foo'},
{id:2, name:'bar'}
]
check(objects, {name: foo}) // true
I think it should be made using map:
我认为应该使用地图制作它:
_.map(objects, function(num, key){ console.log(num.name) });
采纳答案by Marcin
Use find
http://underscorejs.org/#find
使用find
http://underscorejs.org/#find
var check = function (thelist, props) {
var pnames = _.keys(props);
return _.find(thelist, function (obj) {
return _.all(pnames, function (pname) {
return obj[pname] == props[pname];
});
});
};
回答by Florian Margaine
You can use some
for this.
您可以some
为此使用。
check = objects.some( function( el ) {
return el.name === 'foo';
} );
check
is true
if the function returned true
once, otherwise it's false
.
check
是true
如果该函数返回true
一次,否则它false
。
Not supported in IE7/8 however. You can see the MDN link for a shim.
但是在 IE7/8 中不受支持。您可以查看 shim 的 MDN 链接。
For the underscore library, it looks like it's implemented too (it's an alias of any
). Example:
对于下划线库,它看起来也已实现(它是 的别名any
)。例子:
check = _.some( objects, function( el ) {
return el.name === 'foo';
} );