【问题标题】:How to get Object Index by Value?如何按值获取对象索引?
【发布时间】:2015-06-02 09:48:00
【问题描述】:

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,因为没有可以获取的值。

【问题讨论】:

标签: javascript json angularjs


【解决方案1】:

冒昧地将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,那是我的错 - 也注意到另一个错误。试试我现在编辑的那个。我自己运行它,它运行良好。
  • 做到了! :) 谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-26
相关资源
最近更新 更多