更有效的方式来搜索JavaScript对象的数组? [英] More efficient way to search an array of javascript objects?

查看:79
本文介绍了更有效的方式来搜索JavaScript对象的数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

不知道关于发布规则,但我会告诉你,出了大门,这是的这个,但我问这是否是最佳实践的方式来做到这一点?

Not sure about posting rules, but I will tell you out of the gate that this is a repeat question of this one, but I am asking if this is the "best practice" way to do this?

推荐答案

这是直截了当地做到这一点。如果您需要快速访问多次,你应该创建由您要搜索的属性名称键控的地图。

That is the straight forward to do this. If you need fast access multiple times, you should create a map keyed by the property name that you're searching by.

下面是采用阵列并生成密钥的地图功能。它不是万能的,但你应该能够修改供自己使用。

Here's a function that takes arrays and builds keyed maps. It's not all-purpose, but you should be able to modify it for your own use.

/**
 * 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对象的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆