2017-08-03 97 views
0

我正试图在下面的给定数组中搜索userName。当搜索对象数组中的第二个元素时,Search函数对第二个元素返回true,在搜索第一个元素时返回false作为第一个元素。当我们搜索数组中的现有值时,它应该返回true,但函数返回false为第一个元素,为true返回第二个元素。 我找不到我正在做的错误。即使尝试使用Array.prototype.find()函数,但没有运气。虽然搜索值存在于数组中,但JavaScript函数返回else语句

//JSON User Information 
 
var userProfiles = [ 
 
\t { 
 
\t \t "personalInformation" : { 
 
\t \t \t "userName" : "Chandu3245", 
 
\t \t \t "firstName" : "Chandrasekar", 
 
\t \t \t "secondName" : "Mittapalli", 
 
\t \t \t "Gender" : "Male", 
 
\t \t \t "email" : "[email protected]", 
 
\t \t \t "phone" : ["740671xxx8", "8121xxxx74"] 
 
\t \t } 
 
\t }, 
 
\t { 
 
\t \t "personalInformation" : { 
 
\t \t \t "userName" : "KounBanega3245", 
 
\t \t \t "firstName" : "KounBanega", 
 
\t \t \t "secondName" : "Karodpati", 
 
\t \t \t "Gender" : "Male", 
 
\t \t \t "email" : "[email protected]", 
 
\t \t \t "phone" : ["965781230", "8576123046"] 
 
\t \t } 
 
\t } 
 
]; 
 
function findUserDataWithUserID (userData, userid){ 
 
    var fullName = ""; 
 
    //iterates through userData array \t 
 
    userData.forEach(function(user){ 
 
    //checks for matching userid 
 
    if(user.personalInformation.userName === userid){ 
 
    fullName=user.personalInformation.firstName+" "+user.personalInformation.secondName; 
 
    }else{ 
 
     fullName = "Userid Not Found"; 
 
    } 
 
    }); 
 
    return fullName; 
 
} 
 
console.log(findUserDataWithUserID(userProfiles, "Chandu3245"));

+0

向我们展示您尝试使用'Array#find',以及它为什么不起作用。 – 2017-08-03 02:22:13

+0

@torazaburo,我编码类似于上面,但代替forEach我写了array.prototype.find()。当我按照以下建议更正时,它工作正常。 – CHandu3245

回答

0

您也可以使用Array.prototype.some()这个方法。 some方法与every方法类似,但是一直运行到函数返回为止。欲了解更多信息,请访问:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some

function checkProfile (profiles,userid) { 
    var message = "Userid not found" 
    profiles.some(function(user) { 
     if(user.personalInformation.userName === userid) { 
      message = user.personalInformation.firstName+" "+user.personalInformation.secondName; 
    } 
}) 
    console.log(message); 
}; 

checkProfile(userProfiles,"KounBanega3245"); 
0

这是因为它在运行在forEach的第一次迭代的if情况下,则在第二迭代中,它处理所述阵列中的第二项,使得else子句跑。

更全面的方法将是使用过滤器/映射/降低:

userProfiles 
// Only keep the one that we want 
.filter(function(user) { 
    return user.personalInformation.userName === userid; 
}) 
// extract the user's name 
.map(function(user) { 
    return user.personalInformation.firstName + " " + user.personalInformation.secondName; 
}) 
// Get the first (and only) item out of the array 
.pop(); 

这并不解决任何错误检查(如果用户是喜欢不是原始阵列中)。