1

I have the following javascript array:

var vat = [
{ id: '', description: '' },
{ id: 'Zero', description: '0%' },
{ id: 'Six', description: '6%' },
{ id: 'Nineteen', description: '19%' },
{ id: 'TwentyOne', description: '21%' }];

I need to get the description of the element with id of 'Six'. I think it is possible but I did not succeed.

Any help is welcome.

Thanks.

Bronzato
  • 9,438
  • 29
  • 120
  • 212

5 Answers5

5

You could filter the array to leave only the item you are looking for:

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

Note that Array.prototype.filter is an ES5 method and is not supported by older browsers. You can find a polyfill for it in the MDN article linked to previously.

James Allardice
  • 164,175
  • 21
  • 332
  • 312
  • This is of course a valid solution, but I might suggest that if possible, turning 'vat' into an object instead of an array using the ids as the property names. – Tyler Biscoe Jun 12 '13 at 13:17
0

If you know that it is the third item then:

vat[2]['description']

otherwise you could use filter as suggested by James Allardice

Andy G
  • 19,232
  • 5
  • 47
  • 69
0

The structure of your array makes this a bit more complicated than necessary. Here's an alternative structure for which it's much simpler:

var vat = { '': '', 'Zero': '0%' } // and so on
vat['Zero'] // gives '0%'

In case you're stuck with the structure you've got, you'll need a loop. For example:

var result;
for (var i = 0; i < vat.length; i++) {
  if (vat[i].id == 'Six') {
    result = vat[i].description;
    break;
  }
}

PS. the filter method suggested in a different answer makes this easier, but it requires a browser that supports at least JavaScript 1.6.

Jan Krüger
  • 17,870
  • 3
  • 59
  • 51
0

If you want to directly access it, you have to know the position.
Example :

var myDesc = vat[2].description;

Or you can loop on it.
Example :

var myDesc = null
for (i in vat) {
    if (vat[i].id == 'Six')  {
        myDesc = vat[i].desc;
    }
}

Hope it's what you needed.

David Ansermot
  • 6,052
  • 8
  • 47
  • 82
0
    for(var i=0;i < vat.length;i++){
        if(vat[i].id == "Six"){
            alert(vat[i].description);
        }
    }
user23031988
  • 330
  • 2
  • 10