在数组内的JavaScript对象中查找属性的值

时间:2016-09-09 13:59:39

标签: javascript arrays object iterator

我设法从firebase数据库中取回一些用户并将它们输出到控制台

[Object, Object, Object, Object, Object]

每个对象都有:

gender: "male"
liked: "liked"
name: "ed"
not_liked: "liked"
username: "ed@ed.com"
useruid: "HSRcN6PuylXbv87kSWxKVtWffaI3"

如何查看数组并说明useruid的值是否为HSRcN6PuylXbv87kSWxKVtWffaI3,然后console.log()是否为关联名称。在这种情况下ed

我的伪尝试:

if (Object.gender.includes('male')) {
    console.log('yes')
} 
else {
    console.log('nah')
}

2 个答案:

答案 0 :(得分:1)

考虑到您在javascript中将数组存储在dataArray变量中。

for (i = 0; i < dataArray.length; i++) { 
    if(dataArray[i].useruid=="HSRcN6PuylXbv87kSWxKVtWffaI3"){
        console.log(dataArray[i].username);
    }
}

它将在username

的控制台上打印userid=HSRcN6PuylXbv87kSWxKVtWffaI3

答案 1 :(得分:0)

只需循环遍历数组并在找到匹配项时抛出日志。

for(var i = 0; i < arr.length; i++) {
     if(arr[i].useruid === "HSRcN6PuylXbv87kSWxKVtWffaI3") {
          console.log(arr[i].username);
     }
}

至于你的伪尝试:

for(var i = 0; i < arr.length; i++) {
     if(arr[i].gender === "male") {
          console.log("User is male");
     }
     else {
          console.log("User is female");
     }
}