Home > Software engineering >  Can't find the value in Array but when console.log, the value is there
Can't find the value in Array but when console.log, the value is there

Time:11-23

Please refer below console.log output for $scope.levels

enter image description here

And below is the code,

var lvl = _.find($scope.levels, function(l) {
                    return l.levelIndex === level   1;
                });

value for level at this point is 2

However, when I console.log for lvl, it is undefined.

enter image description here

Any idea why it's undefined? And how I can solve this issue?

CodePudding user response:

console what is happening as

console.log({ levelIndex :l.levelIndex , level });

this will show the values with name check if it has value in it and if its returning true

CodePudding user response:

It's entirely possible the value you're checking for is a string, and your strict check is looking for a number. You can cast both sides as a number to test...

var lvl = _.find($scope.levels, function(l) {
   return  l.levelIndex ===  level   1;
});

or in vanilla JS

var lvl = $scope.levels.find(l =>  l.levelIndex ===  level   1);

var level = 2;
var $scope = {levels: [{levelIndex:2},{levelIndex:3}]};
var lvl = $scope.levels.find(l =>  l.levelIndex ===  level   1);
console.log('lvl:',lvl);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related