Reputation: 36937
function countJSONObjByKeyValue(obj, key, value)
{
var countJSONShows = 0;
$.each(obj, function(i, item)
{
if(obj[i].key == value){ countJSONShows++; }
});
alert(countJSONShows);
}
countJSONObjByKeyValue("dashboardJSON.widgets", "show", "false");
is it plausible to think something along the lines there of the function above could work? If so what is wrong with this current function/call to it that I could do to make it work?
I know doing it without the wrapping of a function I can do it just fine but I would like the concept to be reusable.
Upvotes: 0
Views: 486
Reputation: 21762
I don't know what the dashboardJSON.widgets looks like, so I can't tell you 100% of what the problem is.
However, a obvious issue is the way that you are referencing the key. When dealing with JSON, you can reference the key the following two ways:
var o = {"foo":"bar"};
o.foo;
o["foo"];
What you need to do, since you are passing a String value of the key in as a param, you need to use the second way:
obj[i][key]
Upvotes: 1
Reputation: 4084
Should work, however you could also do:
function countJSONObjByKeyValue(obj, key, value)
{
var countJSONShows = 0;
for(x in obj){
if(obj[i].key == value){ countJSONShows++; }
}
window.alert(countJSONShows);
}
countJSONObjByKeyValue(dashboardJSON.widgets, "show", "false");
Also note, obj mustnt be passed as a string
Upvotes: 1