如何根据字符串值查找JSON对象成员

0pt*_*1z3 2 jquery json jsonp getjson

所以我们假设我有一个JSON文件:

{ "store": {
"book": [ 
  { "category": "reference",
    "author": "Nigel Rees",
    "title": "Sayings of the Century",
    "price": 8.95
  },
  { "category": "fiction",
    "author": "Evelyn Waugh",
    "title": "Sword of Honour",
    "price": 12.99
  },
  { "category": "fiction",
    "author": "Herman Melville",
    "title": "Moby Dick",
    "isbn": "0-553-21311-3",
    "price": 8.99
  },
  { "category": "fiction",
    "author": "J. R. R. Tolkien",
    "title": "The Lord of the Rings",
    "isbn": "0-395-19395-8",
    "price": 22.99
  }
    ]
  }
}
Run Code Online (Sandbox Code Playgroud)

我想要做的是抓住"书"的成员及其所有字符串值对,其中标题是"荣誉之剑".我怎么能用JQuery做到这一点?问题是我不知道该成员的索引ID,如果我这样做将是微不足道的,即store.book [1] .XXX会给我所有兄弟键值对的值我正在寻找对于.

有关如何使用最少代码执行此操作的任何想法?

Aln*_*tak 6

使用数组filter:

var matches = store.book.filter(function(val, index, array) {
    return val.title === 'Sword of Honour';
});
Run Code Online (Sandbox Code Playgroud)

结果将是book与过滤谓词匹配的所有元素的数组.

注意:这是一种ES5方法.非ES5浏览器的链接MDN页面上有一个垫片.