0

我试图重写_.where(),这是否:试图重写下划线库_.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})); 

我到底是什么了取回就是改编[]和一个空的“[]”当newArr在年底返回。

+1

首先,在函数中定义'newArr',而不是在外面。其次,请注意,您比较了这些对象,那么简单的'==='将不起作用。 – raina77ow 2014-10-11 20:46:12

+0

好的 - 生病添加newArr的FX,但我不知道如何改变范围将在这里有所作为?我如何访问对象值本身? – rahul2001 2014-10-11 21:00:35

+0

要遍历对象的属性,请使用['for ... in'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in)和['hasOwnProperty'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty)来检查它是对象的属性而不是更下层的对象原型链。 – 2014-10-12 10:50:34

回答

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}));