Javascript – Store function result to variable

javascriptobjectvariables

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.

Best Answer

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.