Sarchophagi
Sarchophagi

Reputation: 386

Error returning an Object

I have an Array of Objects called ENTITIES and the following function that receives and String id and the whole objects Array:

function getEntityById( id, ENTITIES) { id = id.toString(); //made sure id is string

ENTITIES.forEach(function( ENT ) {

  if( ENT.name == id ) {
    return( ENT );
  }

}); }

I've already checked the function with console.log and its working fine. (id is checked and the 'if' is getting TRUE). The problem occurs when i try to access the returned Object 'ENT' outside the function, like this:

var entity0 = getEntityById( 'test', ENTITIES); console.log( entity0.id );

I get the following error: Uncaught TypeError: Cannot read property 'id' of undefined It's like getEntityById function never really returned an Object.

Could you guys help me? Any clues?

Upvotes: 0

Views: 692

Answers (2)

Kiril
Kiril

Reputation: 2963

If you want to return the found entity you have to save it, exit the forEach loop and return the variable:

function getEntityById(id, ENTITIES) {
    var result = null;
    id = id.toString(); //made sure id is string
    ENTITIES.forEach(function( ENT ) {
        if( ENT.name == id ) {
            result = ENT;
        }
    });
    return result;
}

But in that case you'll do some redundant work (if the required entity is found - there's no need to continue the loop). So I would recommend to do like:

function getEntityById(id, ENTITIES) {
    var i = ENTITIES.length;
    while(--i >= 0) {
        if (ENTITIES[i].id === id) {
            return ENTITIES[i];
        }
    }
}

Upvotes: 1

dave
dave

Reputation: 64657

You have this function:

function getEntityById( id, ENTITIES) { 
  id = id.toString(); //made sure id is string
  ENTITIES.forEach(

and then you have this function

    function( ENT ) {
      if( ENT.name == id ) {
      return( ENT );
    }

which returns back to your original function:

  }); 
}

which doesn't do anything with it, so getEntityById returns nothing... so you get undefined.

What you could do is:

function getEntityById( id, ENTITIES) { 
  id = id.toString(); //made sure id is string
  var return_ENT;
  ENTITIES.forEach(function( ENT ) {
    if( ENT.name == id ) {
      return_ENT = ENT;
    }
  }); 
  return return_ENT;
 }

A better option might be to use filter:

function getEntityById( id, ENTITIES) { 
  id = id.toString(); //made sure id is string
  return ENTITIES.filter(function(ent) { return ent.name == id})[0];
};

Upvotes: 1

Related Questions