0

I have created an array of objects which is given below. I want that if I would like to get value from the object which is at any index. When I alert the object using following code it does show start character of the object.

<script>
    var products = {
        DiseaseType: "Respiratory",
        Pathogens: "Actinobacillus   pleuropneumoniae",
        Product: "DRAXXIN® Injectable Solution (tulathromycin)",
        RouteofAdministration: "Injectable",
        DiseaseType: "Respiratory",
        Pathogens: "Actinobacillus pleuropneumoniae",
        Product: "DRAXXIN® 25 Injectable Solution (tulathromycin)",
        RouteofAdministration: "Injectable",
        DiseaseType: "Respiratory",
        Pathogens: "Actinobacillus pleuropneumoniae",
        Product: "EXCEDE® For Swine Sterile Suspension (ceftiofur crystalline free  acid)",
        RouteofAdministration: "Injectable"
    };


alert(products.DiseaseType[0]);
</script>
ivan.mylyanyk
  • 1,963
  • 4
  • 30
  • 37
Sana Riaz
  • 3
  • 1

4 Answers4

0

If you have an array of objects like this :

var products = [{...},{...},{...}]

You can access to a object property with this code :

alert(products[0].DiseaseType);
jmgross
  • 2,256
  • 1
  • 19
  • 21
0

products is an object, not an array. To access its values simply call:

alert(products.DiseaseType)
Alexandru Severin
  • 5,609
  • 10
  • 40
  • 67
0

Well you are assigning scalar values to the element of the object. Hence, this would not return any thing:

alert(products.DiseaseType[0]);

Because you have not declared them like this:

var products = {
        DiseaseType: ["Respiratory"],
        }

Just remove the brackets:

alert(products.DiseaseType[0]);

With {} you care object which do not allows you to access its element using numeric indexes, while [] allows you to declare an array and access its element numerically.

Since String is really, under the hood, not more than an array of character, the following:

var myname = "Robert";
console.log(myname[0]);

returns R because it is treated internally as an array of:

["R", "o", "b", "e", "r", "t"];
Mostafa Talebi
  • 8,010
  • 15
  • 54
  • 97
0

This is an object not array so rather call like this

alert(products.DiseaseType);
R3tep
  • 11,845
  • 10
  • 43
  • 71