简体   繁体   中英

How to fetch the values from object of array

my object is like below

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

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

 } ]

I am using foreach to loop and calculates

 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 ;
});

In the above Beds_Details[0].ICU I am expecting the number but I am getting undefined. How to get the number.

initialize the variable outside the foreach. And also your json missing a , after HospitalAddress : "Address" field

 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) 

Could have to do with the fact that you are missing a , after the HospitalAddress member.

 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); }); 

1- There's a missing comma in your JSON after HospitalAddress

2- You should initialize your Sum_ICU and Sum_Outpatient outside the loop before assigning values.

There is no need of Array in Bed object and because of that it is showing [0].

The updated code is as follows :

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

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

 } ]

And For loop will be as follows:

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 ;
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM