Search an array for matching attribute

前端 未结 8 800
北荒
北荒 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:55

    In this case i would use the ECMAscript 5 Array.filter. The following solution requires array.filter() that doesn't exist in all versions of IE.

    Shims can be found here: MDN Array.filter or ES5-shim

    var result = restaurants.filter(function (chain) {
        return chain.restaurant.food === "chicken";
    })[0].restaurant.name;
    
    0 讨论(0)
  • 2020-12-04 14:55

    you can also use the Array.find feature of es6. the doc is here

    return restaurants.find(item => {
       return item.restaurant.food == 'chicken'
    })
    
    0 讨论(0)
提交回复
热议问题