检索我的javascript数组中的特定元素

Bro*_*ato 1 javascript

我有以下javascript数组:

var vat = [
{ id: '', description: '' },
{ id: 'Zero', description: '0%' },
{ id: 'Six', description: '6%' },
{ id: 'Nineteen', description: '19%' },
{ id: 'TwentyOne', description: '21%' }];
Run Code Online (Sandbox Code Playgroud)

我需要得到description的元素与id"六".我认为这是可能的,但我没有成功.

欢迎任何帮助.

谢谢.

Jam*_*ice 5

您可以filter让数组只保留您要查找的项目:

var desc = vat.filter(function (item) {
    return item.id === "Six";
})[0].description;
Run Code Online (Sandbox Code Playgroud)

请注意,这Array.prototype.filter是一种ES5方法,旧版浏览器不支持.您可以在之前链接的MDN文章中找到它的polyfill.