jquery check value present in an object array - javascript

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?

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;
}

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.
Instead of doing jQuery(this)[0].properties.id, just do this.id, that is not a right syntax.

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

Related

Returning from an anonymous function won't work, even though it's not async

I have the following function:
function filterDesiredURLs(tweet) {
tweet.entities.urls.forEach((url) => {
desiredURLs.forEach((regexPattern) => {
if (regexPattern.test(url['expanded_url'])) {
console.log('hello, im returning');
return true;
}
})
})
}
And I'm calling it like this:
console.log(filterDesiredURLs(tweet));
Where tweet is a defined object. I can see that the function is indeed returning because I see the output hello, im returning in the console, but the console.log(filterDesiredURLs(tweet));prints undefined. I would expect this for anonymous functions passed as callbacks for async operations, but this is not async, so the return should work. What's happening?
return doesn't operate across function boundaries. It only returns from the innermost function. To do what you want you probably want filter or find coupled with some:
function filterDesiredURLs(tweet) {
// First, you were missing a return in the outer function
// Without a return here, *this* function will return `undefined`
return tweet.entities.urls.filter(url => {
// We are using `filter` to reduce the URL list to only
// URLs that pass our test - this inner function needs to return
// a boolean (true to include the URL, false to exclude it)
return desiredURLs.some(regexPattern => {
// Finally, we use `some` to see if any of the regex patterns match
// This method returns a boolean value. If the function passed to it ever
// returns true, it terminates the loop and returns true
// Otherwise, it iterates over the entire array and returns false.
return regexPattern.test(url['expanded_url']);
});
});
}
When you call return like that, you're returning from the closest function (in this case, the anonymous function passed as argument to your inner forEach).
From the docs:
The return statement ends function execution and specifies a value to
be returned to the function caller.
To accomplish your goal, you may try this:
function filterDesiredURLs(tweet) {
let found = false;
tweet.entities.urls.forEach((url) => {
desiredURLs.forEach((regexPattern) => {
if (regexPattern.test(url['expanded_url'])) {
console.log('hello, im returning');
found = true;
/* don't need return because forEach does not expects a function that returns something; and you can't break forEach */
}
})
})
return found;
}
The javascript forEach method returns undefined.
forEach is an operation which retains the array as immutable and returns a new array. In your code, the forEach method is called and it doesn't return anything, hence undefined.

Why is my prototype method returning undefined?

I have created a prototype method that return true and false. The problem is that it doesn't return the value. I know it reaches the statement because I have used console.log() when the condition is met but doesn't return the value.
I cant seem to figure this out. If anyone can help me out here I would really appreciate it. Below is my code
function Validation(){
this.checkRequired = function(){
$(".modifiers-group-cont").each(function(){
var select_opt_notify = $(this).find(".select-option-notify");
/*The radio buttons that are required are always going to be marked check,thats why we are only
* checking for the checkbox*/
if($(this).attr("data-is-checked") == "false" && $(this).attr("data-input-type") == "checkbox"){
select_opt_notify.show();
return false;
} else {
select_opt_notify.hide();
return "true";
}
});
}
function ModifierPost(){
(function(){
$("#add-to-cart").click(function(){
console.log(validation.constructor); //Shows undefined
if(validation.checkRequired()){
$.post("#",$("form").serialize()+ "&item_id=" + item_id);
}
});
})();
}
The return statements belong to the function in each:
$(".modifiers-group-cont").each(function(){
You'll need to expose the values you'd like to return to the outer scope and call return after the call to each.
You have created your function with Capital V and calling with Smaill v in the validation function name
That is the reason it is giving you undefined the place you have mentioned in your code.
console.log(validation.constructor); //Shows undefined
if(validation.checkRequired()){
it should be with Capital V like
console.log(Validation.constructor); //Shows undefined
if(Validation.checkRequired()){

Javascript function returns value.call another function according to first functions return value

sorry this might not be new question but i am new to JS and i didnt get any specific examples for this.
function find(param){
$.each(array,function(i,elem){
if(elem.id==param){
return i;
}
})
return null;
}
//after calling this function i want to perform actions based on result
$(document).on("click","#elem",function(){
//want to make this part synchronous
$.when(i=find(param1)).then(function{
if(i==null)
{//do something
}
else{//do something
}
})
}
i want to perform actions based on return value of find function.and also the conditions should only be checked ater the find function is over.
Your find function will always return null.
$.each(array,function(i,elem){
if(elem.id==param){
return i; //this is each iteration callback scope not find function scope
}
})
The find function should look like this:
function find(param){
var matched=null;
$.each(array,function(i,elem){
if(elem.id==param){
matched=i;
}
})
return matched;
}
Hope this is helpful for you.

Most elegant way to return value from within JQuery $.each?

I was wondering if there a more elegant way of returning a value from the function I've pasted below : "getImageURLforPOICategory".
As you can see I've used JQuery's "each" function to iterate through an array of objects, when I find the matching value I want to return a result out of the "each" loop and then right out of the function that contains the each loop.
I've used a local variable to "cache" it and then I'm returning that. I'm not entirely sure if this is the best approach? Is there a way of returning the value directly from within the each loop?
Tracker.getImageURLforPOICategory = function (POICategoryID) {
var url;
$.each(Tracker.pointofinterestcategories, function () {
if (this.id === POICategoryID) {
url = this.imageurl;
return;
}
}
);
return url;
};
Thanks for reading,
Cheers,
Duncan
No, you can't return a value from the .each().
If you do a return false; it will stop the loop so it isn't running longer than it needs to, but you'll need to use a variable as you're doing now.
If you don't use $.each(), but instead use a for loop, you'll be able to just:
return Tracker.pointofinterestcategories[ i ].imageurl
I'd still use a for loop though.
Tracker.getImageURLforPOICategory = function (POICategoryID) {
return $.grep(Tracker.pointofinterestcategories, function (item) {
return item.id === POICategoryID;
})[0].imageurl;
}

How to break out of .each() and return a value for a function

I want to use return false to break a .each() but also return a value at the same time. How can I do this?
Please refer to a work-around function to see what I am trying to do:
function HasStores(state) {
var statehasstores = false;
$(stores).each(function (index, store) {
if (state == store.state && store.category == "meyers") {
statehasstores = true;
return false; // break
}
});
return statehasstores;
}
What Id like to do in pseudo code is:
Function () {
for() {
if found {
return true;
}
}
return false;
}
You're doing it right...
Quote from http://api.jquery.com/each/
"We can stop the loop from within the callback function by returning false."
Be creative:
try {
$(stores).each(function (index, store) {
if(state == store.state && store.category == "meyers"){
throw store;
}
});
}
catch(e) {
// you got e with the value
}
No, I was just kidding, don't use this :). It came as an idea I liked to share.
Use a variable outside the loop to get the value and use it afterward.
var value;
$(stores).each(function (index, store) {
if(state == store.state && store.category == "meyers"){
statehasstores = true;
value = store; // added line
return false; //break
}
});
alert(value);
The way you're doing is just fine. I've tested on jsFiddle, see an example here.
It's not working for you? Can you show more context?
jQuery .each
Alternatively, you could use a for loop instead of each(), and just return the value.
What you're suggesting is the way to do it. I'd think of it less as a workaround and more as an idiom.
How about:
$.each( myObj, function( key, value ){
...
if( sthg... ){
myObj.somethingWentHorriblyWrong = true;
return false;
}
});
if( myObj.somethingWentHorriblyWrong ){
// ... do something, not forgetting to go:
delete myObj.somethingWentHorriblyWrong;
}
PS I was initially interested in what $.each(... actually returns. As it says on the relevant JQ page, "The method returns its first argument, the object that was iterated", but in fact the solution doesn't even require that you use that fact...
PPS Need a function that returns a value? Wrap in an outer function of course.
Okay I guess there's a little doubt about this point so maybe I'm making it clearer here :
When jquery doc says : "We can stop the loop from within the callback function by returning false." and you do :
Function () {
for() {
if found {
return true;
}
}
return false;
}
This doesn't mean that you're function will return true when find the searched element. Instead, it will always return false.
So to make your function work as you whish I propose to do so :
Function () {
variable found = false;
foreach() {
if found {
found = true;
return false; // This statement doesn't make your function return false but just cut the loop
}
}
return found;
}
Of course there are many other ways to perform this but I think this is the simplest one.
Coopa - Easy !
As others have noted from jQuery Each, returning false will only break from the loop not return the value, returning true however will 'continue' and immediately begin the next iteration. With that knowledge, you could somewhat simplify your code like this:
function HasStores(state) {
var statehasstores = false;
$(stores).each(function (index, store){
// continue or break;
statehasstores = !(state == store.state && store.category == "meyers"))
return statehasstores;
});
return !statehasstores;
}
This of course is a little silly using the double negative, and has the side effect of saving 'true' to statehasstores for every false iteration and vice versa, however the end result should be the same and you no longer have that if statement.

Categories