I want to be able to access the value of a nested each()
function outside of the function.
My approach was to:
- defined the variable outside of the function,
- update it within the function,
- be able to access the updated value outside of the function.
But that doesn't work:
jsFiddle
http://jsfiddle.net/rwone/ESXB4/
jQuery
var my_array = [{"check": "tom", "nested_array": [{"nested_array_2": ["1", "2"], "name": "tom", "image": "one.jpg"}, {"nested_array_2": ["1", "2"], "name": "bob", "image": "two.jpg"}]}];
var check = my_array[0].check;
var desired_value = "hello";
$.each(my_array, function (obj, v) {
$.each(v.nested_array, function (i, value) {
if (value.name == check) {
var desired_value = value.image;
alert(desired_value); // this returns `one.jpg`, the variable has been updated.
}
});
});
//alert(desired_value); // this alerts 'hello', the variable has not been updated.
If the above is the wrong approach, could anyone demonstrate how to access the returned value of a nested each()
loop?
Edit: I should probably say, I was cautious to use a global var at any stage, as this can cause problems later on in the application.
Edit 2: I thought using a global var within the function would forever and always define the variable (unless it was globally defined again), but it doesn't seem to eg:
var desired_value = "hello";
$.each(my_array, function (obj, v) {
$.each(v.nested_array, function (i, value) {
if (value.name == check) {
desired_value = value.image; // 'global'
alert(desired_value); // this returns `one.jpg`, the variable has been updated.
}
});
});
alert(desired_value); // this alerts 'one.jpg', the variable has been updated.
var desired_value = "new value";
alert(desired_value); // this alerts 'new value'
Updated jsFiddle