Search an array for matching attribute

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

提交回复
热议问题