gpt4 book ai didi

javascript - 搜索 javascript 对象数组的更有效方法?

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

不确定发布规则,但我会告诉你这是this one的重复问题,但我想问这是否是“最佳实践”方法?

最佳答案

这是执行此操作的直接方法。如果您需要多次快速访问,您应该创建一个以您要搜索的属性名称为键的 map 。

这是一个接受数组并构建键控映射的函数。它不是通用的,但您应该能够对其进行修改以供自己使用。

/**
* Given an array and a property name to key by, returns a map that is keyed by each array element's chosen property
* This method supports nested lists
* Sample input: list = [{a: 1, b:2}, {a:5, b:7}, [{a:8, b:6}, {a:7, b:7}]]; prop = 'a'
* Sample output: {'1': {a: 1, b:2}, '5': {a:5, b:7}, '8': {a:8, b:6}, '7':{a:7, b:7}}
* @param {object[]} list of objects to be transformed into a keyed object
* @param {string} keyByProp The name of the property to key by
* @return {object} Map keyed by the given property's values
*/
function mapFromArray (list , keyByProp) {
var map = {};
for (var i=0, item; item = list[i]; i++) {
if (item instanceof Array) {
// Ext.apply just copies all properties from one object to another,
// you'll have to use something else. this is only required to support nested arrays.
Ext.apply(map, mapFromArray(item, keyByProp));
} else {
map[item[keyByProp]] = item;
}
}
return map;
};

关于javascript - 搜索 javascript 对象数组的更有效方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4653114/

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