![](/img/trans.png)
[英]Compare two arrays in react and filter one based on matches of name property
[英]Ramda compare two arrays of objects based on one property
我有 2 個 arrays:
arr1 = [
{
id: "1",
name: "Test 1"
},
{
id: "2",
name: "Test 2"
}
]
arr2 = [
{
groupId: "125",
age: 44,
subGroup: {
id: "1",
name: "Test 1"
}
}
]
使用 Ramda,我需要比較 arr1 和 arr2,並根據 id (id: "1") 從 arr2 返回匹配的 object
所以結果應該是:
[
{
groupId: "125",
age: 44,
subGroup: {
id: "1",
name: "Test 1"
}
}
]
使用R.innerJoin()
在兩個 arrays ( arr2
和arr1
)之間相交,並從第一個數組(在您的情況下為arr2
)獲取項目:
const fn = R.innerJoin((a, b) => a.subGroup?.id === b.id) const arr1 = [{"id":"1","name":"Test 1"},{"id":"2","name":"Test 2"}] const arr2 = [{"groupId":"125","age":44,"subGroup":{"id":"1","name":"Test 1"}},{"groupId":"126","age":46}] const result = fn(arr2, arr1) console.log(result)
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.min.js"></script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.