Sunday, June 2, 2024
 Popular · Latest · Hot · Upcoming
26
rated 0 times [  33] [ 7]  / answers: 1 / hits: 26705  / 12 Years ago, wed, february 27, 2013, 12:00:00

How can I store the result of a function to a variable?



In navigating an object that contains an array, I am looking for one value, value1, once that is found I want to get the value of one of its properties, property1.



The code I am using below is an example and is incorrect.



function loadSets(id){
clworks.containers.find(function(i){
return i.get('property1')===id;
});
}


My intent is to navigate the object below:



clworks.containers
containers[0].property0.id
containers[1].property1.id


I am trying to determine how to find which item in the array has a property value equal to the id used in the function and then store it as a variable.


More From » variables

 Answers
109

Simply:



var myVar = loadSets(id);


EDIT



Ok, as much as I understand your question now, your situation is the following:




  1. You have an array containing objects called containers;

  2. You want to iterate through this array, looking for the property id of the property property1 which equals the one specified in the function called loadSets(id);

  3. Once found, store the object with the requested id in a variable.



Am I right?
If so, this should solve your problem:



// This function iterates through your array and returns the object
// with the property id of property1 matching the argument id
function loadSets( id ) {

for(i=0; i < containers.length; i++) {

if( containers[i].property1.id === id )
return containers[i];

}

return false;

}


After this you just need to do what I said in the first answer to your question, triggering it however you want. I put up a quick JSBin for you. Try to put 10, or 20, in the input field and then hitting the find button; it will return the object you are looking for. Try putting any other number, it will return a Not found.


[#79958] Tuesday, February 26, 2013, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
wyattkennyc

Total Points: 650
Total Questions: 102
Total Answers: 90

Location: Monaco
Member since Mon, May 23, 2022
2 Years ago
;