感谢this post,其中接受的答案包括JS小提琴,我能够验证我可以使用jQuery.grep()过滤我的数据。但是,我无法使用服务器的输出复制效果。我怀疑我在对象引用中忽略了一些明显的东西,但对JavaScript不熟悉我认为我需要有人为我指出它。
这是我的数据输出,一个对象数组:
[{"id":"3","src":"url1","category":"A"},
{"id":"32","src":"url2","category":"D"},
{"id":"38","src":"url3","category":"E"},
{"id":"39","src":"url4","category":"E"},
{"id":"42","src":"url5","category":"F"},
{"id":"49","src":"url6","category":"B"},
{"id":"44","src":"url7","category":"F"}]
我使用以下代码过滤F类中的条目:
var obj = [{"id":"3","src":"url1","category":"A"},
{"id":"32","src":"url2","category":"D"},
{"id":"38","src":"url3","category":"E"},
{"id":"39","src":"url4","category":"E"},
{"id":"42","src":"url5","category":"F"},
{"id":"49","src":"url6","category":"B"},
{"id":"44","src":"url7","category":"F"}];
obj = $.grep(obj, function(element, index){
return element.category == "F" // keep elements in category F
});
console.log(obj);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
&#13;
这是我对服务器的Ajax调用:
var obj = $.post( url, {term: term }, function(data){
}, 'json'
);
执行console.log(obj);
时,我在控制台中将我的数据输出视为对象,但似乎无法实现。要使grep函数起作用,我需要以对象数组的形式访问输出。它在那里,等着我,但我该如何参考呢?
答案 0 :(得分:1)
当你这样做时:
var obj = $.post( url, {term: term }, function(data){
}, 'json');
obj
是承诺而非响应数据
您需要访问成功回调
中的响应数据$.post( url, {term: term }, function(data){
var obj = $.grep(data, function(element, index){
return element.category == "F" // keep elements in category F
});
console.log(obj);
}, 'json' );