0

"I'm adding a property on array while in a forEach loop. But when I do the console.log() the added value on each array is always the last value of the foreach loop."

deliveries data has location and I want to pass the location to pickupDetails.

   deliveries: [{  //data of deliveries that I want to pass in pickupDetails
     0: {Location: Korea},
     1: {Location: Japan}
   }]

   let pickupDetails = this.state.pickupDetails;

   //pickupDetails is only one object then It will become two since the deliveries has 2 objects
   pickupDetails = {
      name: "June"
   }


   this.state.deliveries.forEach((delivery, index) => {
       pickupDetails.location = delivery.location;
       console.log(pickupDetails)
   })

   the result of the console:
   pickupDetails = {
       name: "June"
       location: "Japan" //this should be Korea since the first loop data is korea
   }
   pickupDetails = {
       name: "June"
       index: "Japan"
   }
Jay Ar Viluan
  • 59
  • 2
  • 10
  • Why it should be index 0? your code do looping of course it will set to last index of array. – William Gunawan Aug 03 '19 at 10:17
  • How can I add each index in every loop then? – Jay Ar Viluan Aug 03 '19 at 10:18
  • 2
    You need to provide dummy data for this.state.deliveries too so we can see your pattern and please tell us more what do you want. before data process and expected after process data. it will be great help to understand your question – William Gunawan Aug 03 '19 at 10:19
  • I've edited and provided a sample william. Thank you – Jay Ar Viluan Aug 03 '19 at 10:24
  • The issue you mention is discussed [here](https://stackoverflow.com/questions/23392111/console-log-async-or-sync). When you console.log an object and you update it right after, the console.log will show the updated value. – Tasos K. Aug 03 '19 at 10:24

1 Answers1

0

I think something missing from that code maybe because its dummy data. alright from my point of view you confused with javascript reference.

deliveries: [{  //data of deliveries that I want to pass in pickupDetails
     0: {Location: Korea},
     1: {Location: Japan}
   }]

   let pickupDetails = this.state.pickupDetails;
   this.state.deliveries.forEach((delivery, index) => {
       let newPickupDetails = JSON.parse(JSON.stringify(pickupDetails));
       newPickupDetails.location = delivery.location;
       console.log(newPickupDetails);
   })

   the result of the console:
   pickupDetails = {
       name: "Juan"
       location: "Japan" //this should be Korea since the first loop data is korea
   }
   pickupDetails = {
       name: "June"
       index: "Japan"
   }

JSON.parse and JSON.stringify we use for create new object instead of use reference. console log effected because it linked by reference so if you make it new object it will do.

Check variable newPickupDetails

William Gunawan
  • 748
  • 3
  • 8