按内部数组值过滤数组

时间:2016-08-07 09:29:16

标签: javascript

我有一个对象,其中包含一个如下所示的数组:

{
    "media": [
        {
            "title": "Raiders of the Lost Ark",
            "year": "1981",
            "poster": "http://ia.media-imdb.com/images/M/MV5BMjA0ODEzMTc1Nl5BMl5BanBnXkFtZTcwODM2MjAxNA@@._V1_SY1000_CR0,0,664,1000_AL_.jpg",
            "genre": ["action", "adventure"],
            "type": "movie"
        },
        {
            "title": "The Other Guys",
            "year": "2010",
            "poster": "http://ia.media-imdb.com/images/M/MV5BMTc0NDQzNTA2Ml5BMl5BanBnXkFtZTcwNzI2OTQzMw@@._V1_.jpg",
            "genre": ["action", "comedy", "crime"],
            "type": "movie"
        }
    ]
}

我正在尝试创建一个过滤函数,该函数将返回具有特定类型的所有项目。

这是我制作的过滤器,但似乎没有返回任何值。

//pretend movies equals my parsed JSON file 
const Movies = json.media; 

const Filter = function(array, key, value){
    let i, j, filteredResults = [], item;

    for(i =  0, j = array.length; i<j; i++){
        item = array[i];
        if(typeof item[key] !== "undefined" && item[key] === value){
            filteredResults.push(item);
        }
    }

    return filteredResults;
}

console.log(Filter(Movies, "genre", "action"));

这不会返回任何值但是应该返回一个包含2部电影的数组吗?

7 个答案:

答案 0 :(得分:4)

您可以使用过滤方法

var medias = [
    {
        "title": "Raiders of the Lost Ark",
        "year": "1981",
        "poster": "http://ia.media-imdb.com/images/M/MV5BMjA0ODEzMTc1Nl5BMl5BanBnXkFtZTcwODM2MjAxNA@@._V1_SY1000_CR0,0,664,1000_AL_.jpg",
        "genre": ["action", "adventure"],
        "type": "movie"
    },
    {
        "title": "The Other Guys",
        "year": "2010",
        "poster": "http://ia.media-imdb.com/images/M/MV5BMTc0NDQzNTA2Ml5BMl5BanBnXkFtZTcwNzI2OTQzMw@@._V1_.jpg",
        "genre": ["action", "comedy", "crime"],
        "type": "movie"
    }
]
sortedMedias = medias.filter(elem => elem.genre.indexOf("crime")!=-1);
console.log(sortedMedias); //  [ { title: 'The Other Guys',
                           //      year: '2010',
                           //      poster: 'http://ia.media-imdb.com/images/M/MV5BMTc0NDQzNTA2Ml5BMl5BanBnXkFtZTcwNzI2OTQzMw@@._V1_.jpg',
                           //      genre: [ 'action', 'comedy', 'crime' ],
                           //      type: 'movie' } ]

答案 1 :(得分:3)

你快到了。只有一点需要改变:

  • 'genre'属性本身就是一个数组,所以'indexOf'就是'action' 必须检查参数

    const Filter = function(obj, key, value) {
        let i, j, filteredResults = [], item;
    
        // The media property is the array in which we want to search 
        let array = obj.media;
    
        for(i =  0, j = array.length; i < j; i++){
            item = array[i];
    
            // the genre property is itself an array
            // so we'll need to find the 'indexOf' the item
            // rather than comparing directly
    
            if(typeof item[key] !== "undefined" && item[key].indexOf(value) !== -1){
                filteredResults.push(item);
            }
        }
    
        return filteredResults;
    }
    

答案 2 :(得分:0)

使用此

if(_.contains(item[key], value)){
  filteredResults.push(item);
}

而不是

if(typeof item[key] !== "undefined" && item[key] === value){
  filteredResults.push(item);
}

答案 3 :(得分:0)

我认为你应该保持简单。我也许这样的事情适合你

function movieFilter (where, field, search) {
  if (typeof search !== "string") { search = search.toString()}; //for example if you want to search by the year, and you provide integer search number
  return where.filter(item => {
    return item[field].toLowerCase().indexOf(search.toLowerCase()) !== -1;
  })
}

这是此功能的游乐场示例 https://jsbin.com/tepifa/edit?js,console

答案 4 :(得分:0)

如果您正在尝试制作通用过滤器功能,则应考虑以下几种情况:

  • 严格平等(===)
  • 松散平等(==)
  • partOf

var d = {
  "media": [{
    "title": "Raiders of the Lost Ark",
    "year": "1981",
    "poster": "http://ia.media-imdb.com/images/M/MV5BMjA0ODEzMTc1Nl5BMl5BanBnXkFtZTcwODM2MjAxNA@@._V1_SY1000_CR0,0,664,1000_AL_.jpg",
    "genre": ["action", "adventure"],
    "type": "movie"
  }, {
    "title": "The Other Guys",
    "year": "2010",
    "poster": "http://ia.media-imdb.com/images/M/MV5BMTc0NDQzNTA2Ml5BMl5BanBnXkFtZTcwNzI2OTQzMw@@._V1_.jpg",
    "genre": ["action", "comedy", "crime"],
    "type": "movie"
  }]
}
var _g = "action";
function filter(array, key, value, operation) {
  return array.filter(x=>{
    switch(operation){
      case "contains": return x[key].indexOf(value)>-1;
      case "ignoreType": return x[key] == value;
      default: return x[key] === value;
    }
  })
}
console.log(filter(d.media, "genre", "action", "contains"))
console.log(filter(d.media, "year", 2010))
console.log(filter(d.media, "year", 2010, "ignoreType"))

答案 5 :(得分:0)

    item[key].forEach(function(oneDoc){

        if(oneDoc == value){
            filteredResults.push(item);
        }
    })

答案 6 :(得分:0)

首先需要找到价值指数。如果索引不是-1,则表示值在数组中有效。

for(i =  0, j = array.length; i<j; i++){
    item = array[i];
    if(typeof item[key] !== "undefined" && item[key].indexOf(value) !==    -1 ){
        filteredResults.push(item);
    }
}