kevin_marcus
kevin_marcus

Reputation: 277

Get array within an object

I am trying to get the array value from the object I created but seems like that obj.item is not working to me. It always saying undefined here's my code::

$.each(componentSentenceArray, function(index,item) { 
          conole.log(item.item_name)

});

and here is my object

ingredient:
Array(3)
0:{item_name: "Albenza", uom_code: "", uom_desc: "", amount: ""}
1:{item_name: "Baclofen", uom_code: "", uom_desc: "", amount: ""}
2:{item_name: "Lasix", uom_code: "", uom_desc: "", amount: ""}


main_component:
Array(1)
0 :{item_name: "Lasix", uom_code: "", uom_desc: "", amount: ""}

Upvotes: 0

Views: 78

Answers (3)

Makarand Patil
Makarand Patil

Reputation: 1001

$(document).ready(function() {
  var componentSentenceArray = {
    ingredient: [{
        item_name: "Albenza",
        uom_code: "",
        uom_desc: "",
        amount: ""
      },
      {
        item_name: "Baclofen",
        uom_code: "",
        uom_desc: "",
        amount: ""
      },
      {
        item_name: "Lasix",
        uom_code: "",
        uom_desc: "",
        amount: ""
      }
    ],
    main_component: [{
      item_name: "Lasix",
      uom_code: "",
      uom_desc: "",
      amount: ""
    }]
  };

  $.each(componentSentenceArray, function(index, item) {
    $.each(item, function(index, item1) {
      console.log(item1.item_name);
    });
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

This should work for you. You are having array list inside and object which you should loop again to access its variable.

  $.each(componentSentenceArray, function(index,item) { 
    $.each(item, function(index,item1) { 
      console.log(item1.item_name);    
    });
  });

Upvotes: 2

simbathesailor
simbathesailor

Reputation: 3687

$.each(componentSentenceArray, function(index,item) { 
     $.each(item, function(index, arrayItem) {
       console.log(arrayItem.item_name)
     })
});

This should help

Upvotes: 1

Chathura Edirisinghe
Chathura Edirisinghe

Reputation: 367

$.each(componentSentenceArray, function (key, data) {
    console.log(key)
    $.each(data, function (index, data) {
        console.log('index', data)
    })
})

this will work!

Upvotes: 2

Related Questions