Search an array for matching attribute

前端 未结 8 801
北荒
北荒 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;
    

提交回复
热议问题