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.

3

5 Answers 5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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.
0

If you know that it is the third item then:

vat[2]['description']

otherwise you could use filter as suggested by James Allardice

3 Comments

It's an array of object, so the description is accessed by . not []
@mArm.ch, using brackets is perfectly valid. Look up javascript bracket notation.
It would be necessary as well, if the key (the attribute) contained spaces.
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.

Comments

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.

Comments

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

2 Comments

Could you explain your answer please?
I added a piece of code that extracts in the vat[i].description the description of the element with id of 'Six'.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.