【问题标题】:Check if an array of objects have a key value using underscore使用下划线检查对象数组是否具有键值
【发布时间】:2012-05-28 17:25:42
【问题描述】:

如何使用下划线检查对象数组是否具有键值。

例子:

var objects = [
  {id:1, name:'foo'},
  {id:2, name:'bar'}
]

check(objects, {name: foo}) // true

我认为应该使用地图制作:

_.map(objects, function(num, key){ console.log(num.name) });

【问题讨论】:

    标签: javascript functional-programming underscore.js


    【解决方案1】:

    使用findhttp://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];
            });
        });
    };
    

    【讨论】:

      【解决方案2】:

      您可以为此使用some

      check = objects.some( function( el ) {
          return el.name === 'foo';
      } );
      

      如果函数返回一次true,则checktrue,否则为false

      但在 IE7/8 中不支持。您可以查看 shim 的 MDN 链接。

      对于下划线库,它看起来也实现了(它是any 的别名)。示例:

      check = _.some( objects, function( el ) {
          return el.name === 'foo';
      } );
      

      【讨论】:

      • 检查数组中是否有一个这样的对象怎么样?
      猜你喜欢
      • 1970-01-01
      • 2021-12-10
      • 2019-03-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-12
      • 1970-01-01
      相关资源
      最近更新 更多