繁体   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