如何通过值获取对象索引?

5

由Fissio回答

我正在尝试在Angular中制作一个简单的搜索功能。当用户在输入框中输入内容时,我希望能够搜索我的JSON中的所有“标题”,如果某个词与输入匹配,则带回与匹配相关的所有对象。

工厂

我首先创建了一个工厂,使用Promise从JSON中检索数据。

.factory('podcastData', function($http) {

var podcastData = {

    async: function() {
        var promise = $http.get('http://radio-sante-animale.fr/podcast-data.php').then(function(response) {
            return response.data.categories;
        })
        return promise;
    }

};

return podcastData;

})

然后在我的控制器中,我尝试在控制器中编写一个搜索程序。 目前为止,我已经成功使用for循环,获取了数组的长度,然后获取了数组中的所有“播客”,最后成功将所有匹配输入值的值获取到。

控制器

更新

$scope.findValue = function(enteredValue) {
    console.log(enteredValue);
    var filtered = [];
    podcastData.async().then(function(data) {
        for (i = 0; i < data.length; i++) {
            angular.forEach(data[i].podcasts, function(podcasts, key) {

                var foundPodcasts = _.filter(podcasts, function(podcast) {                       
                    return podcasts.title.toLowerCase().indexOf(enteredValue) >= 0
                });

                if (typeof foundPodcasts !== 'undefined') {
                    filtered.concat(foundPodcasts);
                    console.log(foundPodcasts);
                };                 
            });
        }
    });

}

我已更新控制器,现在我可以返回所有与搜索输入匹配的对象,但是当我使用console.log打印 foundPodcasts 时,我的响应如下图所示。这很好!然而,数组之间是空的,并且我无法使用NG-REPEAT,因为没有值可供我获取。

enter image description here


1
你能展示一下"data"的JSON吗?它包含哪些属性? - Huy Hoang Pham
嗨,Anon,当然可以!http://radio-sante-animale.fr/podcast-data.php - anon
1个回答

2

我自作主张将filtered转换为数组; 我理解你想要找到所有匹配的电影,而在你的代码中,你只是在每次匹配时重新创建了filtered对象。

$scope.findValue = function(enteredValue) {
    var filtered = [];
    podcastData.async().then(function(data) {
        for (i = 0; i < data.length; i++) {
            var foundPodcasts = _.filter(data[i].podcasts, function(podcast) {
                return podcast.title.toLowerCase().indexOf(enteredValue) >= 0
            });
            if (typeof foundPodcasts !== 'undefined') {
                filtered = filtered.concat(foundPodcasts);
            };
        }
    console.log(filtered);
    return filtered;
});

谢谢您的帮助,但是在您的返回值中'podcast.title.toLowerCase()...',找不到podcast.title,我正在尝试弄清楚如何获取标题值。 - anon
@anon,那是我的错 - 我还注意到了另一个错误。现在请尝试我编辑过的代码。我自己运行了一下,它可以正常工作。 - Fissio
这样就可以了! :) 谢谢 - anon

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接