繁体   English   中英

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

[英]More efficient way to search an array of javascript objects?

不知道发帖规则,但我会告诉你,出了大门,这是一个重复的问题这一个 ,但我问这是否是“最佳实践”的方式来做到这一点?

这是直截了当的做法。 如果您需要多次快速访问,则应创建一个由您正在搜索的属性名称键入的地图。

这是一个采用数组和构建键控映射的函数。 这不是万能的,但你应该能够修改它以供自己使用。

/**
 * 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;
};

@jondavidjohn - 你可以使用这个javascript lib,DefiantJS( http://defiantjs.com ),你可以使用它在JSON结构上使用XPath过滤匹配。 把它放在JS代码中:

var data = [
   {
      "restaurant": {
         "name": "McDonald's",
         "food": "burger"
      }
   },
   {
      "restaurant": {
         "name": "KFC",
         "food": "chicken"
      }
   },
   {
      "restaurant": {
         "name": "Pizza Hut",
         "food": "pizza"
      }
   }
].
res = JSON.search( data, '//*[food="pizza"]' );

console.log( res[0].name );
// Pizza Hut

这是一个工作小提琴;
http://jsfiddle.net/hbi99/weKVL/

DefiantJS使用方法“search”扩展全局对象,并返回一个匹配的数组(如果没有找到匹配,则返回空数组)。 您可以在此处使用XPath Evaluator尝试lib和XPath查询:

http://www.defiantjs.com/#xpath_evaluator

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM