从多个参数中过滤嵌套对象

时间:2014-06-22 11:57:50

标签: javascript lodash

我希望能够使用嵌套对象搜索数组中的所有值。搜索参数不应该是一个字符串,而是一个像这样的字符串数组:['1970','comedy','family']

我如何用lodash解决这个问题?我已经尝试了一段时间而无法解决这个问题。

测试数据:

var movies = [
    {
        id: 1, 
        title: '22 Jump Street',
        category: 'Comedy',
        description: 'After making their way through high school (twice), big changes are in store for officers Schmidt and Jenko when they go deep undercover at a local college',
        director: {
            name: 'Phil',
            lastName: 'Lord',
            dob: '12-07-1975'
        },

    },
    {
        id: 2, 
        title: 'How to Train Your Dragon 2',
        category: 'Animation',
        description: 'When Hiccup and Toothless discover an ice cave that is home to hundreds of new wild dragons and the mysterious Dragon Rider, the two friends find themselves at the center of a battle to protect the peace.',
        director: {
            name: 'Dean',
            lastName: 'DeBlois',
            dob: '07-06-1970'
        },

    },
    {
        id: 3, 
        title: 'Maleficent',
        category: 'Family',
        description: 'A vengeful fairy is driven to curse an infant princess, only to discover that the child may be the one person who can restore peace to their troubled land.',
        director: {
            name: 'Robert',
            lastName: 'Stromberg',
            dob: '22-08-1970'
        },

    }
];

1 个答案:

答案 0 :(得分:1)

@Aprillion评论的扩展答案:

function filterMovies(query) {
    var params = Array.prototype.slice.call(query);
    var result = movies;

    params.forEach(function(param) {
        result = result.filter(function(movie) {
           return JSON.stringify(movie).indexOf(param) >= 0;
        });
    });

    return result;
}

console.log('filtered: ', filterMovies(['1970', 'Robert']));