[英]Replace IDs (strings) in array with references to full objects from another array
I have a source array of "full objects": 我有一个“完整对象”的源数组:
[
{
"_id": "5b4f9fda7911cf35ef13652d",
"index": 0,
"guid": "498f7981-d51f-4904-9441-e182a9f816a1",
"isActive": true,
"balance": "$3,621.74",
"picture": "http://placehold.it/32x32"
},
{
"_id": "5b4f9fdafe3a9a34a23b2384",
"index": 1,
"guid": "4d51b6bd-cde1-4537-ab04-00279d31819a",
"isActive": true,
"balance": "$2,255.20",
"picture": "http://placehold.it/32x32"
},
{
"_id": "5b4f9fda630056748bab5ef1",
"index": 2,
"guid": "4eafecbf-61d6-430c-83d7-a5cbca464ba2",
"isActive": true,
"balance": "$3,831.17",
"picture": "http://placehold.it/32x32"
},
{
"_id": "5b4f9fdacf21ab443543eaf5",
"index": 3,
"guid": "ebbf0837-e651-442f-b2dd-683ca7566e1c",
"isActive": true,
"balance": "$2,306.59",
"picture": "http://placehold.it/32x32"
},
{
"_id": "5b4f9fda29a6076af6fe2653",
"index": 4,
"guid": "c3336d60-7adc-424d-b9d9-2a79388296a2",
"isActive": true,
"balance": "$2,618.71",
"picture": "http://placehold.it/32x32"
},
{
"_id": "5b4f9fdad82474982243c996",
"index": 5,
"guid": "ad98afcf-b347-4b4c-89ff-60e610eb6429",
"isActive": true,
"balance": "$2,785.16",
"picture": "http://placehold.it/32x32"
}
]
And I have order array that defines specific order of these items: 我有一个订单数组,用于定义这些项目的特定顺序:
[
"5b4f9e23c98e0e6e6b80a078",
"5b4f9e232a1e3cb66de39da6",
"5b4f9e232a4c2cd581820b5e",
"5b4f9e23cea38324b6dc088b",
"5b4f9e230fda7c3f47fdcc44",
"5b4f9e23d8dc8781b55c2d9f",
"5b4f9e23a2722749bd0cf007",
"5b4f9e2337826857f21913e2",
"5b4f9e23a90929808423cc78",
"5b4f9e23d5f0dc1ea1de2fa9",
"5b4f9e23c3a98a8d62895f52",
"5b4f9e2321a33c977199a30f",
"5b4f9e231217cf22adf41d88",
"5b4f9e239616ddcd8894fc8f",
"5b4f9e23a503781b1c281c79",
"5b4f9e2394bf6e7543f77c80",
"5b4f9e23a59a30678ecfe6a6",
"5b4f9e239cbea626e1ef9771",
"5b4f9e238bca46582cc4245c",
"5b4f9e2354eba1b141ad4ebe"
]
What I want is to write a method that would: 我要写的是一种方法:
How can I do that? 我怎样才能做到这一点?
Turn your source array into a map for easy look up: 将您的源数组转换为地图以便于查找:
const byID = new Map(source.map(el => [el.id, el]));
Then you can easily turn the sorted array into references: 然后,您可以轻松地将排序后的数组转换为引用:
sorted = sorted.map(id => byID.get(id));
To remove an (the fith in this example) element: 要删除(在此示例中为fith)元素:
sorted.splice(4, 1)
so if I delete an item from the "source" - it gets deleted from the "order" 因此,如果我从“源”中删除一个项目-它从“订单”中删除
Thats impossible, you have to manually remove it from the sorted array. 那是不可能的,您必须手动将其从已排序的数组中删除。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.