我有2個數組,我試圖在第二個數組中找到與第一個數組中的對象的Id相匹配的數組對象。從那裏我需要追加匹配的對象到主對象。我也只需要通過鍵值獲取前3個匹配對象。我一直在用Underscore進行嘗試,但是這隻會將匹配的數組合並在一起。這就是我所需要的,任何幫助都會很棒。通過匹配值搜索輔助數組併合併到主數組中
var primaryArray = [
{
"Name": "Main 1",
"Id": "1"
},
{
"Name": "Main 2",
"Id": "2"
}
]
var secondaryArray = [
{
"name": "Person 1",
"mainitemId": "1",
"count": 120
},
{
"name": "Person 2",
"mainitemId": "1",
"count": 80
},
{
"name": "Person 3",
"mainitemId": "1",
"count": 125
},
{
"name": "Person 4",
"mainitemId": "1",
"count": 130
},
{
"name": "Person 5",
"mainitemId": "2",
"count": 90
},
{
"name": "Person 6",
"mainitemId": "2",
"count": 85
},
{
"name": "Person 7",
"mainitemId": "2",
"count": 105
},
{
"name": "Person 8",
"mainitemId": "2",
"count": 110
}
]
var resultArray = [
{
"Name": "Main 1",
"Id": 1,
"people": [
{
"name": "Person 4",
"mainitemId": "1",
"count": 130
},
{
"name": "Person 3",
"mainitemId": "1",
"count": 125
},
{
"name": "Person 1",
"mainitemId": "1",
"count": 120
}
]
},
{
"Name": "Main 2",
"Id": 2,
"people": [
{
"name": "Person 8",
"mainitemId": "2",
"count": 110
},
{
"name": "Person 7",
"mainitemId": "2",
"count": 105
},
{
"name": "Person 5",
"mainitemId": "2",
"count": 90
}
]
}
]
您已經嘗試了什麼? –
您正在尋找幾件事情,合併數組,按對象值搜索並可能進行排序以確定排名前3(**決定top3的**是什麼?**)。網上有很多例子說明如何做每個部分。挑一個並嘗試一下。如果您在代碼方面存在問題,請將其發佈到此處,然後查看它。此外,請參閱[**我如何提出一個好問題**](https://stackoverflow.com/help/how-to-ask)以及如果適用,使用您自己的代碼來解決問題,[* *如何創建一個最小化,完整和可驗證的示例**](https://stackoverflow.com/help/mcve) – Nope