簡體   English   中英

使用findIndex查找和更新對象中深層嵌套數組的性能

[英]Finding and updating performance on deeply nested Arrays in Objects with findIndex

我有以下數據結構:

const myData = [
        {
            "trips": [
                {
                    "destination": "Hungary",
                    "id": "34547",
                    "stars": 0
                },
                {
                    "destination": "Hungary",
                    "id": "14542",
                    "stars": 0
                },
                {
                    "destination": "Hungary",
                    "id": "88247",
                    "stars": 0
                },
                {
                    "destination": "Hungary",
                    "id": "11447",
                    "stars": 0
                },
            ],
            "descr": "Holidays",
            "id": "243567"
        },
    ]

假設我們有N個具有唯一ID的對象:

給定項id ,行程id和替換行程對象,找到並替換行程對象。

例:

const itemId = 243567;
const tripId = 14542;

const replacement = { 
  destination: Beijing
  id: 14542
  stars: 4
};;

我的解決方案如下:

 const myData = [{ "trips": [{ "destination": "Hungary", "id": "34547", "stars": 0 }, { "destination": "Hungary", "id": "14542", "stars": 0 }, { "destination": "Hungary", "id": "88247", "stars": 0 }, { "destination": "Hungary", "id": "11447", "stars": 0 }, ], "descr": "Holidays", "id": "243567" }]; const itemId = 243567; const tripId = 14542; const replacement = { destination: "Beijing" id: 14542 stars: 4 }; const itemIndex = myData .findIndex(element => element.id === itemId); const tripIndex = myData[itemIndex].trips .findIndex(element => element.id === tripId); Object.assign(myData[itemIndex].trips[tripIndex], replacement); 

該解決方案將如何執行?是否有更快的實施方法?

如果您只需要對給定的數據集執行一次這樣的查找和變異,那么您當前的工作就可以了。

但是,如果您將在同一數據集中執行多次查找和更改(因此在重新加載之前),則應按ID和Trip ID鍵入數據。 為此,您可以使用此函數,在加載數據集后應調用一次:

 function hashData(myData) { const result = {}; for (const row of myData) { const obj = result[row.id] = {}; for (const trip of row.trips) { obj[trip.id] = trip; } } return result; } // Sample data const myData = [{ "trips": [{"destination": "Hungary", "id": "34547", "stars": 0 },{"destination": "Hungary", "id": "14542", "stars": 0 },{"destination": "Hungary", "id": "88247", "stars": 0 },{"destination": "Hungary", "id": "11447", "stars": 0}], "descr": "Holidays", "id": "243567"}]; // Key it by id and trip id: const hash = hashData(myData); // Mutate one particular entry: Object.assign(hash[243567][88247], { destination: 'PARADISE', id: "9999", stars: 5 }); // Display result console.log(myData); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

如果您不介意更多冗長的代碼,那么使用單獨的分配替換Object.assign將在當前瀏覽器中提供更好的性能:

const obj = hash[243567][88247];
obj.destination = 'PARADISE';
obj.id = "9999";
obj.stars = 5;

暫無
暫無

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

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