gpt4 book ai didi

javascript - 如何按值获取对象索引?

转载 作者:搜寻专家 更新时间:2023-11-01 04:31:00 25 4
gpt4 key购买 nike

由 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;

})

然后在我的 Controller 中,我尝试在我的 Controller 中执行一个搜索程序。到目前为止,我尝试了一个 for 循环,我得到了数组的长度,然后我得到了数组中的所有“播客”,然后我设法得到了与输入匹配的所有值。

Controller

已更新

$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);
};
});
}
});

}

我更新了我的 Controller ,现在我确实返回了与搜索输入匹配的所有对象,但是当我在 console.log foundPodcasts 时,这是我的回应。这很好!但是,中间有空数组,我无法执行 NG-REPEAT,因为没有我可以获取的 VALUE。

enter image description here

最佳答案

擅自将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;
});

关于javascript - 如何按值获取对象索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30592663/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com