1

Thanks to this post, in which the accepted answer includes a JS Fiddle, I was able to verify that I can filter my data using jQuery.grep(). However, I am not able to replicate the effect using output from my server. I suspect I am overlooking something obvious in the object referencing, but being new to JavaScript I think I need someone to point it out for me.

This is my data output, an array of objects:

[{"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"}]

I use the following code to filter entries within category 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>

This is my Ajax call to the server:

var obj = $.post( url, {term: term }, function(data){
}, 'json'
);

When performing console.log(obj); I find my data output as an Object in the console, but can't seem to get to it. For the grep function to work, I need to access the output as an array of objects. It is there, waiting for me, but how do I reference it?

Community
  • 1
  • 1
  • The result of `grep` is an array of objects. [MDN Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#Accessing_array_elements) – pishpish Jul 13 '16 at 12:39
  • Always use triple equals (===) when doing string comparisons. – Samuel Lindblom Jul 13 '16 at 13:18
  • @Samuel, why === and not ==? Both seem to work in my case – guiltybyintent Jul 13 '16 at 16:22
  • It is a best practice, where === also does type checking and is therefore more predictable. Here is some more information: http://stackoverflow.com/questions/359494/does-it-matter-which-equals-operator-vs-i-use-in-javascript-comparisons. – Samuel Lindblom Jul 13 '16 at 19:59

1 Answers1

1

When you do:

var obj = $.post( url, {term: term }, function(data){
}, 'json');

obj is a promise not the response data

You need to access the response data inside the success callback

$.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' );
charlietfl
  • 170,828
  • 13
  • 121
  • 150