Reputation: 7289
I am trying to check if a value is present inside an array of object
function hasProperties(id){
jQuery(JSON.parse(jQuery("#PropertiesField").html())).each(function () {
if(id== jQuery(this)[0].properties.id) {
console.log((id== jQuery(this)[0].properties.id));
return "Present";
}
})
};
var something = hasProperties("someid");
the above snippet returns undefined
for something
, but also true is logged in console. why is it not returning present
when condition satisfies, what is the mistake that I have done?
Upvotes: 3
Views: 79
Reputation: 7289
I found the issue, the return i had is for the .each()
. I added a return outside the foreach function and it works now
function hasProperties(id){
var found =false;
jQuery(JSON.parse(jQuery("#PropertiesField").html())).each(function () {
if(id== jQuery(this)[0].properties.id) {
console.log((id== jQuery(this)[0].properties.id));
found= true;
return;
}
})
return found;
};
var something = hasProperties("someid");
Upvotes: 0
Reputation: 3570
The function provided in the each method is an anonymous inner function. Therefore, nothing is returned outside of each() context. To tackle this you can do something like,
function getProperty(id){
var result;
$('your element').each(function(){
//If your condition is true
result=expectedValue
});
return result;
}
Upvotes: 1
Reputation: 36703
#PropertyField
html as JSON and then want to make its jQuery object. Do a check on it.jQuery(this)[0].properties.id
, just do this.id
, that is not a right syntax.Upvotes: 1