[英]Array within object returning length of 0, even though there are elements present
[英]Object not found within array even though it is
我有2個對象數組( allUsers
和friendsOnTrip
)。 這兩個數組的格式相同。 其中的每個對象都包含用戶的詳細信息(即firstName
和lastName
)。 我試圖使一個數組中的一個對象不在另一個數組中,然后將該對象推到一個新的數組中,否則不要這樣做。
allUsers.forEach((user) => {
if (friendsOnTrip.indexOf(user) <= -1) {
this._friendsNotOnTrip.push(user);
}
});
問題是,即使對象user
看起來像在friendsOnTrip
,也可以使用friendsOnTrip
表達式:
if (friendsOnTrip.indexOf(user) <= -1)
...仍將評估為true
(這是錯誤的),因此我最終在this._friendsNotOnTrip
了不應存在的對象。
對象之一的示例:
{
email: "foo@bar.com",
firstName: "foo",
lastName: "bar",
key: "123456789",
friends: [
"987654321",
"246808642"
],
location: {
lng: -1.24567,
lat: 50.9865
},
usersToSeeLocation: [
"987654321"
]
}
allUsers
位於位置0的對象和friendsOnTrip
中位於位置0的對象是同一對象。 我測試了各個屬性,並得到以下結果:
console.log(allUsers[0].firstName === friendsOnTrip[0].firstName); //true
console.log(allUsers[0].lastName === friendsOnTrip[0].lastName); //true
console.log(allUsers[0].email === friendsOnTrip[0].email); //true
console.log(allUsers[0].friends === friendsOnTrip[0].friends); //false
console.log(allUsers[0].key === friendsOnTrip[0].key); //true
console.log(allUsers[0].location === friendsOnTrip[0].location); //false
console.log(allUsers[0].usersToSeeLocation === friendsOnTrip[0].usersToSeeLocation); //false
console.log(allUsers[0] === friendsOnTrip[0]); //false
在allUsers[0]
和friendsOnTrip[0]
friends
, usersToSeeLocation
和location
中,內容完全相同,因此我不確定為什么這些表達式求值為false
。
您無法比較這樣的對象。 例如
[{a: 1, b:2}].indexOf({a: 1, b:2})
返回-1。 相反,您應該搜索特定的屬性,例如
allUsers.forEach((user) => {
if (friendsOnTrip.map(u => u.key).indexOf(user.key) <= -1) {
this._friendsNotOnTrip.push(user);
}
});
“查看朋友,usersToSeeLocation和allUsers [0]和friendsOnTrip [0]中的位置,它們的內容是完全相同的,因此我不確定這些表達式為何被評估為false。”
那是因為它們不一樣。 具有相同的值,但它們不是同一對象! 這就是為什么您的“ ===”返回false您必須一一比較所有索引
您可以執行array1.join()=== array2.join()以更快地進行比較
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.