将数组中的 ID(字符串)替换为对另一个数组中完整对象的引用

Replace IDs (strings) in array with references to full objects from another array

我有一个 source 数组 "full objects":

[
  {
    "_id": "5b4f9fda7911cf35ef13652d",
    "index": 0,
    "guid": "498f7981-d51f-4904-9441-e182a9f816a1",
    "isActive": true,
    "balance": ",621.74",
    "picture": "http://placehold.it/32x32"
  },
  {
    "_id": "5b4f9fdafe3a9a34a23b2384",
    "index": 1,
    "guid": "4d51b6bd-cde1-4537-ab04-00279d31819a",
    "isActive": true,
    "balance": ",255.20",
    "picture": "http://placehold.it/32x32"
  },
  {
    "_id": "5b4f9fda630056748bab5ef1",
    "index": 2,
    "guid": "4eafecbf-61d6-430c-83d7-a5cbca464ba2",
    "isActive": true,
    "balance": ",831.17",
    "picture": "http://placehold.it/32x32"
  },
  {
    "_id": "5b4f9fdacf21ab443543eaf5",
    "index": 3,
    "guid": "ebbf0837-e651-442f-b2dd-683ca7566e1c",
    "isActive": true,
    "balance": ",306.59",
    "picture": "http://placehold.it/32x32"
  },
  {
    "_id": "5b4f9fda29a6076af6fe2653",
    "index": 4,
    "guid": "c3336d60-7adc-424d-b9d9-2a79388296a2",
    "isActive": true,
    "balance": ",618.71",
    "picture": "http://placehold.it/32x32"
  },
  {
    "_id": "5b4f9fdad82474982243c996",
    "index": 5,
    "guid": "ad98afcf-b347-4b4c-89ff-60e610eb6429",
    "isActive": true,
    "balance": ",785.16",
    "picture": "http://placehold.it/32x32"
  }
]

我有 order 数组定义了这些项目的特定顺序:

[
    "5b4f9e23c98e0e6e6b80a078",
    "5b4f9e232a1e3cb66de39da6",
    "5b4f9e232a4c2cd581820b5e",
    "5b4f9e23cea38324b6dc088b",
    "5b4f9e230fda7c3f47fdcc44",
    "5b4f9e23d8dc8781b55c2d9f",
    "5b4f9e23a2722749bd0cf007",
    "5b4f9e2337826857f21913e2",
    "5b4f9e23a90929808423cc78",
    "5b4f9e23d5f0dc1ea1de2fa9",
    "5b4f9e23c3a98a8d62895f52",
    "5b4f9e2321a33c977199a30f",
    "5b4f9e231217cf22adf41d88",
    "5b4f9e239616ddcd8894fc8f",
    "5b4f9e23a503781b1c281c79",
    "5b4f9e2394bf6e7543f77c80",
    "5b4f9e23a59a30678ecfe6a6",
    "5b4f9e239cbea626e1ef9771",
    "5b4f9e238bca46582cc4245c",
    "5b4f9e2354eba1b141ad4ebe"
]

我想要的是编写一个方法:

我该怎么做?

将源数组转换为地图以便于查找:

const byID = new Map(source.map(el => [el.id, el]));

然后就可以很方便的把排序后的数组转成引用了:

sorted = sorted.map(id => byID.get(id));

删除一个(本例中的第 fith)元素:

sorted.splice(4, 1)

so if I delete an item from the "source" - it gets deleted from the "order"

那是不可能的,你必须手动将它从排序数组中删除。