Finding a property in a JSON Object
javascript, jquery, json
Solution
jQuery.inArray returns -1 when element is not found. That's `true` value from the POV of Javascript. Try this:
if($.inArray('foo', tags.jane) != -1) {
Problem
I'm creating a JSON object like ``` tags = {"jon":["beef","pork"],"jane":["chicken","lamb"]}; ``` which was generated using php from an array like ``` $arr = array( 'jon' => array('beef', 'pork'), 'jane' => array('chicken', 'lamb') ); $tags = json_encode($arr); ``` And I want to check if something is in one or the other. None of these seem to work, but something like ``` if('lamb' in tags.jane)) { console.log('YES'); } else { console.log('NO'); } ``` writes NO to the console ``` if('foo' in tags.jane)) { console.log('YES'); } else { console.log('NO'); } ``` also writes NO to the console so looking at ``` typeof(tags.jane); ``` it shows it's an `"object"` but ``` console.log(tags); ``` shows the following: ``` Object jane: Array[2] 0: "chicken" 1: "lamb" length: 2 __proto__: Array[0] jon: Array[2] 0: "beef" 1: "pork" length: 2 __proto__: Array[0] __proto__: Object ``` so i thought maybe `tags.jane` may actually be an array and tried ``` if($.inArray('lamb', tags.jane)) { console.log('YES'); } else { console.log('NO'); } ``` which writes YES to the console but ``` if($.inArray('foo', tags.jane)) { console.log('YES'); } else { console.log('NO'); } ``` also writes YES to the console. Am I incorrectly building the JSON Object? Not targeting the value(s) properly? Any advice is greatly appreciated. If this would be easier as an array instead of an object, I have full control to change it. I'm just a bit stumped at how I should treat this.