[英]Check if one property of two elements from different arrays are equal?
目前我一直在使用嵌套的 for 循環來解決這個問題:
for (var i = 0; i < this.props.trackedPlayers.length; i++)
{
for (var j = 0; j < PHP_VARS.players_data.length; j++)
{
// This check here is the key part
if (PHP_VARS.players_data[j]._id == this.props.trackedPlayers[i]._id)
{
data.push(// stuff from both arrays..);
}
}
}
但是我認為可能已經有一個樣板函數可以做到這一點。 進行了幾次搜索,但沒有任何結果 - 任何提示,或者這是我目前最好的嗎?
編輯:簡要說明,trackedPlayers 均來自players_data。 通過檢查(通常)較大的players_data 中的每個玩家是否在trackedPlayers 中,我知道是否將它們列為“添加”到HTML 選擇字段的選項。
您可以使用一個對象作為哈希表並遍歷兩個數組,首先用於構建哈希表,第二次用於測試和進一步操作。
var object = Object.create(null);
this.props.trackedPlayers.forEach(function (a) {
object[a._id] = a;
});
PHP_VARS.players_data.forEach(function (a) {
if (object[a._id]) {
// access data from this.props.trackedPlayers
// with object[a._id]._id as example
// access data from PHP_VARS.players_data
// with a._id as example
data.push(/* stuff from both arrays..*/);
}
});
lodash 庫有_.intersectionBy()
函數,它完全符合你的要求。 使用它,您可以將代碼更改為:
_.intersectionBy([PHP_VARS.players_data, this.props.trackedPlayers], "_id")
.forEach(element=> {
data.push(/* ... */)
})
或者,使用for...of
循環:
const intersection = _.intersectionBy([PHP_VARS.players_data, this.props.trackedPlayers], "_id")
for (element of intersection) {
data.push(/* ... */)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.