More efficient way to search an array of javascript objects?

后端 未结 2 761
终归单人心
终归单人心 2020-12-30 17:35

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

相关标签:
2条回答
  • 2020-12-30 17:44

    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;
    };
    
    0 讨论(0)
  • 2020-12-30 17:52

    @jondavidjohn - you can use this javascript lib, DefiantJS (http://defiantjs.com), with which you can filter matches using XPath on JSON structures. To put it in JS code:

    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
    

    Here is a working fiddle;
    http://jsfiddle.net/hbi99/weKVL/

    DefiantJS extends the global object with the method "search" and returns an array with matches (empty array if no matches were found). You can try out the lib and XPath queries using the XPath Evaluator here:

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

    0 讨论(0)
提交回复
热议问题