在对象中获取数组

时间:2017-11-13 05:28:08

标签: javascript jquery object

我试图从我创建的对象中获取数组值,但似乎obj.item对我不起作用。它总是说undefined这里是我的代码::

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

});

这是我的对象

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: ""}

3 个答案:

答案 0 :(得分:2)



$(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>
&#13;
&#13;
&#13;

这对你有用。你有一个数组列表和对象,你应该再次循环访问它的变量。

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

答案 1 :(得分:2)

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

这会有效!

答案 2 :(得分:1)

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

这应该有帮助