【问题标题】:More efficient way to search an array of javascript objects?搜索 javascript 对象数组的更有效方法?
【发布时间】:2011-06-06 21:21:29
【问题描述】:

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

【问题讨论】:

    标签: javascript arrays json search


    【解决方案1】:

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

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

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

    【讨论】:

      【解决方案2】:

      @jondavidjohn - 您可以使用这个 javascript 库 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

      【讨论】:

        猜你喜欢
        • 2014-10-31
        • 1970-01-01
        • 1970-01-01
        • 2016-08-14
        • 1970-01-01
        • 2014-05-24
        • 2018-10-21
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多