Vignesh Subramanian
Vignesh Subramanian

Reputation: 7289

jquery check value present in an object array

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

Answers (3)

Vignesh Subramanian
Vignesh Subramanian

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

Imesha Sudasingha
Imesha Sudasingha

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

void
void

Reputation: 36703

  1. I don't think you actually want to parse #PropertyField html as JSON and then want to make its jQuery object. Do a check on it.
  2. Instead of doing jQuery(this)[0].properties.id, just do this.id, that is not a right syntax.

Upvotes: 1

Related Questions