簡體   English   中英

javascript-Lodash中的javascript對象哈希與lodash foreach刪除

[英]javascript object hash vs lodash foreach in lodash remove

我正在嘗試從復雜對象中刪除一些數據。

原始數據的格式如下。

let originData = 
[
    {
       name : exampleDepth1,
       depth1Data : 
       [
            {
                 name : exampleDepth2,
                 depth2Data : 
                 [
                     {
                         code: 1234///will be delete from that data
                     },
                     ...
                 ]
            },
            ...
        ]
    },
    ....
]

let willbeDeletecode = [ 3, 100, 1234, 1000];

要刪除的陣列的名稱是code中值depth2Data的陣列originData ,陣列刪除的名稱是willbeDeletecode

對不起,如果您不舒服。

我正在嘗試以兩種方式擦除它。

let deleteBook = {}
_.forEach(willbeDeletecode, (deleteCode) => {
  deleteBook[`${deleteCode}`] = deleteCode;
})

_.remove(originData, (depth1) => {
  _.remove(depth1.depth1Data, (depth2) => {
    /*
    // delete with object hash
    _.remove(depth2.depth2Data, (eachDepth2Data) => {
      return deleteBook[eachDepth2Data.code] === undefined
    })
    */

    /*
    // delete with forEach
    let ret = false;
     _.remove(depth2.depth2Data, (eachDepth2Data) => {
       _.forEach(willbeDeletecode, (deleteCode) => {
         if(deleteCode === eachDepth2Data.code){
             ret = true;
             return false;
            }
        })
        return ret
    })
    */
    return depth2.depth2Data.length === 0;
  })
  return depth1.depth1Data.length === 0;
})

我有兩種單獨的注釋方式。

第一種是創建一個對象( deleteBook )並插入willbeDeletecode的數據,並將其用於除去lodash中。

第二種方法完全是通過forEach函數進行的所有比較。

重復上述方法1000次以進行基准測試。 結果,第一種方法為100〜200ms,第二種方法為500〜700ms。

當然, willbeDeletecode大約在10左右,但是我認為對象哈希更快。 但是結果卻相反。

如果willbeDeletecode有更多變量,還會有另一個結論嗎? 我想知道為什么會這樣。

對象哈希是首選。 您也可以將ES6 Set用於此目的。

這樣的哈希解決方案應該更快。

您沒有看到這種情況的一個原因是,代碼的第一個變體消除了應有的反面 _remove回調應在刪除相應項時返回true值,但是當該值不在應刪除的代碼中時,代碼將返回true 您應該使用!==比較:

_.remove(depth2.depth2Data, (eachDepth2Data) => {
    return deleteBook[eachDepth2Data.code] !== undefined
})

當您在此處===時,可能要進行更多的清除操作,因此執行時間更長。

暫無
暫無

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

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