gpt4 book ai didi

javascript - 我可以更改 key 对数据的存储方式以使访问非常高效吗?

转载 作者:行者123 更新时间:2023-11-30 10:21:35 25 4
gpt4 key购买 nike

我有以下包含用户数据的数组。该数据中只有大约 20 个元素。我从我的服务器获取它并存储在本地:

var userdata1 = 
[
{"id":"527ddbd5-14d3-4fb9-a7ae-374e66f635d4","name":"xxx"},
{"id":"e87c05bc-8305-45d0-ba07-3dd24438ba8b","name":"yyy"}
]

我一直在使用以下函数从我的 userProfiles 数组中获取用户名。

  $scope.getUser = function (userId) {
if (userId && $scope.option.userProfiles)
for (var i = 0; i < $scope.option.userProfiles.length; i++)
if ($scope.option.userProfiles[i].id === userId)
return $scope.option.userProfiles[i].name;
return '';
}

我正在寻找一种更有效的方法来获取名称,所以我问了这个问题:

How can I check an array for the first occurence where a field matches using _lodash?

现在我想知道。有没有其他方法可以存储我的数据以使其更易于访问?一个人建议这个在评论中:

var usersdata2 = {someuserid: {id: "someusersid", name: 'Some Name'}, 
anotheruserid: {id: "anotheruserid", name: 'Another Name'}};

如果我这样做会不会更有效率,我怎样才能将我的数据从第一种形式 userdata1 更改为 userdata2我如何访问它?

最佳答案

您可以按如下方式转换数组:

var userMap = userdata1.reduce(function(rv, v) {
rv[v.id] = v;
return rv;
}, {});

这将为您提供一个将“id”值映射到原始对象的对象。然后,您将像这样访问这些值:

var someUser = userMap[ someUserId ];

此设置将比您的数组更有效率,因为查找条目所花费的时间与“id”字符串本身的大小成正比(加上一点)。在您的版本中,每次查找都必须(平均)搜索一半的列表。对于一小部分记录,差异并不重要,但如果您有成百上千条记录,差异将是巨大的。

.reduce() 函数在旧版浏览器中不可用,but there's a fill-in patch available on the MDN documentation site:

// copied from MDN
if ('function' !== typeof Array.prototype.reduce) {
Array.prototype.reduce = function(callback, opt_initialValue){
'use strict';
if (null === this || 'undefined' === typeof this) {
// At the moment all modern browsers, that support strict mode, have
// native implementation of Array.prototype.reduce. For instance, IE8
// does not support strict mode, so this check is actually useless.
throw new TypeError(
'Array.prototype.reduce called on null or undefined');
}
if ('function' !== typeof callback) {
throw new TypeError(callback + ' is not a function');
}
var index, value,
length = this.length >>> 0,
isValueSet = false;
if (1 < arguments.length) {
value = opt_initialValue;
isValueSet = true;
}
for (index = 0; length > index; ++index) {
if (this.hasOwnProperty(index)) {
if (isValueSet) {
value = callback(value, this[index], index, this);
}
else {
value = this[index];
isValueSet = true;
}
}
}
if (!isValueSet) {
throw new TypeError('Reduce of empty array with no initial value');
}
return value;
};
}

关于javascript - 我可以更改 key 对数据的存储方式以使访问非常高效吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21311981/

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