如何从数组的对象中获取值

时间:2017-05-10 12:48:46

标签: javascript angularjs

我的对象如下

Facility = [{
       HospitalName : "one",
       HospitalAddress : "Address"
       Beds : [{ICU : 6, 
                Outpatient : 7}]

 }, {
       HospitalName : "Two",
       HospitalAddress : "Address"
       Beds : [{ICU : 2, 
                Outpatient : 15}]

 } ]

我使用foreach循环并计算

 Facility.forEach(function (element) {

   var Beds_Details = element.Beds;
  console.log(Beds_Details);   // Here I am getting Icu and all in [0]
   Sum_ICU  += Beds_Details[0].ICU ;   //Here getting undefined
   Sum_Outpatient  += Beds_Details[0].Outpatient ;
});

在上面的 Beds_Details [0] .ICU 中,我期待这个数字,但我没有定义。如何获得号码。

4 个答案:

答案 0 :(得分:0)

在foreach之外初始化变量。而且你的json在,字段

之后错过HospitalAddress : "Address"



var Facility = [{
       HospitalName : "one",
       HospitalAddress : "Address",
       Beds : [{ICU : 6, 
                Outpatient : 7}]

 }, {
       HospitalName : "Two",
       HospitalAddress : "Address",
       Beds : [{ICU : 2, 
                Outpatient : 15}]

 } ]
 var Sum_Outpatient = '';
 var Sum_ICU = 0;
 Facility.forEach(function (element) {debugger 
   var Beds_Details = element.Beds;

   Sum_ICU  += parseInt(Beds_Details[0].ICU) ;  
   Sum_Outpatient  += Beds_Details[0].Outpatient ;
   
});


   console.log(Sum_ICU)




答案 1 :(得分:0)

可能与,成员之后错过HospitalAddress这一事实有关。



var facility = [{
       HospitalName : "one",
       HospitalAddress : "Address",
       Beds : [{ICU : 6, 
               Outpatient : 7}]

 }, {
       HospitalName : "Two",
       HospitalAddress : "Address",
       Beds : [{ICU : 2, 
                Outpatient : 15}]

 }];


facility.forEach(function (element) {

   var Beds_Details = element.Beds;
   console.log(Beds_Details);          // Here I am getting Icu and all in [0]
   console.log(Beds_Details[0].ICU);   // Here getting undefined
   console.log(Beds_Details[0].Outpatient);
});




答案 2 :(得分:0)

1-在HospitalAddress

之后,您的JSON中缺少逗号

2-您应该在分配值之前在循环外初始化Sum_ICUSum_Outpatient

答案 3 :(得分:0)

Bed对象中不需要Array,因为它显示[0]。

更新的代码如下:

Facility = [{
       HospitalName : "one",
       HospitalAddress : "Address",
       Beds : {ICU : 6, 
                Outpatient : 7}

 }, {
       HospitalName : "Two",
       HospitalAddress : "Address",
       Beds : {ICU : 2, 
                Outpatient : 15}

 } ]

For循环如下:

Sum_ICU=0;
Sum_Outpatient=0;
Facility.forEach(function (element) {
   var Beds_Details = element.Beds;
  console.log(Beds_Details);   // Here I am getting Icu and all in [0]
   Sum_ICU  += Beds_Details.ICU ;   //Here getting undefined
   Sum_Outpatient  += Beds_Details.Outpatient ;
});