簡體   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