3

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?

3 Answers 3

1

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;
}
Sign up to request clarification or add additional context in comments.

Comments

1
  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.

2 Comments

thanks, now i am using this.properties.id, but the problem persists it is logging "true" in console, but the value is not getting assigned to the var
@vignesh just do this.id
0

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");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.