簡體   English   中英

用對另一個數組中完整對象的引用替換數組中的ID(字符串)

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

我有一個“完整對象”的數組:

[
  {
    "_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"
  }
]

我有一個訂單數組,用於定義這些項目的特定順序:

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

我要寫的是一種方法:

  • 替換參照的ID(字符串)在源對象
  • 因此,如果我從“源”中刪除一個項目-它從“訂單”中刪除
  • 但是,如果我從“訂單”中刪除項目,則不會從源中刪除該項目

我怎樣才能做到這一點?

將您的源數組轉換為地圖以便於查找:

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

然后,您可以輕松地將排序后的數組轉換為引用:

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

要刪除(在此示例中為fith)元素:

sorted.splice(4, 1)

因此,如果我從“源”中刪除一個項目-它從“訂單”中刪除

那是不可能的,您必須手動將其從已排序的數組中刪除。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM