Search an array for matching attribute

前端 未结 8 799
北荒
北荒 2020-12-04 14:16

I have an array, I need to return a restaurant\'s name, but I only know the value of its \"food\" attribute (not it\'s index number).

For example, how could I return

相关标签:
8条回答
  • 2020-12-04 14:33

    Must be too late now, but the right version would be:

    for(var i = 0; i < restaurants.restaurant.length; i++)
    {
      if(restaurants.restaurant[i].food == 'chicken')
      {
        return restaurants.restaurant[i].name;
      }
    }
    
    0 讨论(0)
  • 2020-12-04 14:33

    you can use ES5 some. Its pretty first by using callback

    function findRestaurent(foodType) {
        var restaurant;
        restaurants.some(function (r) {
            if (r.food === id) {
                restaurant = r;
                return true;
            }
       });
      return restaurant;
    }
    
    0 讨论(0)
  • 2020-12-04 14:39
    for(var i = 0; i < restaurants.length; i++)
    {
      if(restaurants[i].restaurant.food == 'chicken')
      {
        return restaurants[i].restaurant.name;
      }
    }
    
    0 讨论(0)
  • 2020-12-04 14:42
    let restaurant = restaurants.find(element => element.restaurant.food == "chicken");
    

    The find() method returns the value of the first element in the provided array that satisfies the provided testing function.

    in: https://developer.mozilla.org/pt-PT/docs/Web/JavaScript/Reference/Global_Objects/Array/find

    0 讨论(0)
  • 2020-12-04 14:45

    @Chap - 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
    

    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)
  • 2020-12-04 14:53
    for (x in restaurants) {
        if (restaurants[x].restaurant.food == 'chicken') {
            return restaurants[x].restaurant.name;
        }
    }
    
    0 讨论(0)
提交回复
热议问题