gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 03:16:41 25 4
gpt4 key购买 nike

我有以下数据结构:

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 和行程 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;

关于javascript - 使用 findIndex 查找和更新对象中深度嵌套数组的性能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46747903/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com