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
  • 2,051
  • 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,306
  • 1
  • 20
  • 24
0

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

alert(products.DiseaseType)
Alexandru Severin
  • 6,021
  • 11
  • 48
  • 71
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,825
  • 16
  • 61
  • 105
0

This is an object not array so rather call like this

alert(products.DiseaseType);
R3tep
  • 12,512
  • 10
  • 48
  • 75