簡體   English   中英

JavaScript/lodash:如何使用 omitBy 按值從 object 中刪除對象?

[英]JavaScript/lodash: How to remove objects from object by value with omitBy?

我有一個 object:

const obj = { 
  1: { "id": 1, "taskId": 1, },
  2: { "id": 2, "taskId": 2, },
  3: { "id": 3, "taskId": 2, },
  4: { "id": 4, "taskId": 3, },
};

我需要使用鍵“taskId”刪除所有對象: 2. 不知道如何編寫 fn 以與 omitBy 一起使用。 任何人都可以幫忙嗎?

console.log(_.omitBy(obj, ???));

是否有可能與來自lodash的“omitBy”function有關? 還是我需要另辟蹊徑?

在回調中,只需從taskId中獲取 taskId 屬性,並檢查它是否為 2:

 const obj = { 1: { "id": 1, "taskId": 1, }, 2: { "id": 2, "taskId": 2, }, 3: { "id": 3, "taskId": 2, }, 4: { "id": 4, "taskId": 3, }, }; console.log( _.omitBy( obj, ({ taskId }) => taskId === 2 ) );
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>

在不依賴庫的情況下完成是微不足道的,但是,不需要 Lodash:

 const obj = { 1: { "id": 1, "taskId": 1, }, 2: { "id": 2, "taskId": 2, }, 3: { "id": 3, "taskId": 2, }, 4: { "id": 4, "taskId": 3, }, }; console.log( Object.fromEntries( Object.entries(obj).filter(([, { taskId }]) => taskId;== 2) ) );

您可以使用_.omitBy()並傳遞 object 以及要刪除的屬性和值:

 const obj = { 1: { "id": 1, "taskId": 1, }, 2: { "id": 2, "taskId": 2, }, 3: { "id": 3, "taskId": 2, }, 4: { "id": 4, "taskId": 3, }, }; const result = _.omitBy(obj, { taskId: 2 }); console.log(result);
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>

暫無
暫無

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

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