使用findIndex查找和更新对象中深层嵌套数组的性能

时间:2017-10-14 18:19:31

标签: javascript

我有以下数据结构:

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);

此解决方案将如何执行,是否有更快的方法来实现它?

1 个答案:

答案 0 :(得分:1)

如果你只需要为给定的数据集执行一次这样的查找和变异,那么你目前所做的就没那么了。

但是,如果您在同一数据集中执行多个查找和突变(因此在重新加载之前),那么您应该按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;