1

I am trying to return object from function but it returns nothing any idea?

var todo = [{
    id: 'a01',
    titre: 'Citation',
    message: 'Vous êtes de ceux-là ? Ca tombe bien, je lai été moi aussi !',
    completed: false
}];

getById: function(todoId) {
    for (var i = 0; i < todo.length; i++) {
        if (todo[i].id == todoId) {
            return todo;
        }
    }
}
4
  • you are returning the full array Commented May 2, 2016 at 11:46
  • probably you want to return todo[i] Commented May 2, 2016 at 11:46
  • use return todo[i]; Commented May 2, 2016 at 11:47
  • what value did you passed to getById method? Commented May 2, 2016 at 11:47

2 Answers 2

2

return the array element instead of the complete array:

getById: function(todoId){
    for(var i=0;i<todo.length;i++){
        //console.log(todo[i].id == todoId);
        if(todo[i].id == todoId){
            return todo[i];
        }
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Can you explain me why u use todo[i] with indice ?
maybe the result will be clearer for you if you use console.debug(todo);console.debug(todo[i]); and check out the console output (hit F12 and find Console)
-1

Try this code:

var todo=[{
    id:'a01',
    titre:'Citation',
    message:'Vous êtes de ceux-là ? Ca tombe bien, je lai été moi aussi !',
    completed:false
}];

var getById = function(todoId){
    for(var i=0;i<todo.length;i++){
        //console.log(todo[i].id == todoId);
        if(todo[i].id == todoId){
            return todo[i];
        }
    }
}

3 Comments

It will be return todo[i]; instead of return todo[0];
Yes, I changed it. @SirajulHaq
Edited to fix the index. You can run this code in your console followed by getById('a01').

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.