试图在Underscore库中重写_.where函数

时间:2014-10-11 20:44:10

标签: javascript arrays object functional-programming underscore.js

我正在尝试重写执行此操作的_.where():

where_.where(列表,属性) 查看列表中的每个值,返回包含属性中列出的所有键值对的所有值的数组。

我无法访问数组中作为属性传递给where()的不同对象。如何访问数组中对象的值并对其进行迭代?

这就是我所拥有的:

 var arr = [{title: "Cymbeline", author: "Shakespeare", year: 1611},
               {title: "The Tempest", author: "Shakespeare", year: 1611},
               {title: "Cymbeline", author: "steve", year: 1671}];
    var newArr = [];
    var where = function (list, properties) {
        for (var i = 0; i < list.length; i++){
            console.log(list[i]); // just gives the array again??
            if (list[i] == properties) {// this conditional should compare the values in arr and     properties
                newArr.push(list[i]); // if the values in arr match those in properties then the        respective objects get pushed to newArr
        }
        }
        return newArr;
    }


console.log(where(arr, {author: "Shakespeare", year: 1611}));

我最终得到的是arr []和空的&#34; []&#34;当最后返回newArr时。

1 个答案:

答案 0 :(得分:0)

OP想要的是过滤具有可配置(不断变化的)条件的列表,但是这种配置如何影响过滤过程的固定思维模式(算法)。

要清楚这一点,可以直截了当地实现一个完全正确的函数...从提供的propertyMap构建过滤条件并在过滤提供的列表时利用它。

不知道where应该如何实施...... whereEverywhereSome上述主要方法非常灵活,可以提供两种不同的变体Array.every分别为Array.some ...

var list = [{
  title: "Cymbeline",
  author: "Shakespeare",
  year: 1611
}, {
  title: "The Tempest",
  author: "Shakespeare",
  year: 1611
}, {
  title: "Cymbeline",
  author: "steve",
  year: 1671
}];


var where = function (list, propertMap) {
  var
    keyList   = Object.keys(propertMap),

    condition = function (item) {             // where every.
      return keyList.every(function (key) {
        var
          property = item[key]
        ;
        return (!!property && (property === propertMap[key]));
      });
    }
  ;
  return list.filter(condition);
};

console.log(where(list, {author: "Shakespeare", year: 1611}));
console.log(where(list, {author: "Shakespeare"}));
console.log(where(list, {author: "Shakespeare", title: "Cymbeline"}));
console.log(where(list, {title: "Cymbeline"}));


var whereSome = function (list, propertMap) {
  var
    keyList   = Object.keys(propertMap),

    condition = function (item) {             // where some.
      return keyList.some(function (key) {
        var
          property = item[key]
        ;
        return (!!property && (property === propertMap[key]));
      });
    }
  ;
  return list.filter(condition);
};

console.log(where(list, {author: "steve", year: 1611}));
console.log(whereSome(list, {author: "steve", year: 1611}));