从多个参数中筛选嵌套对象

Filtering nested object from multiple parameres

本文关键字:筛选 嵌套 对象 参数      更新时间:2023-09-26

我希望能够搜索具有嵌套对象的数组中的所有值。搜索参数不应该是字符串,而是像这样的字符串数组:['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'
        },
    }
];

@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']));