Pankaj Sonava
Pankaj Sonava

Reputation: 623

How to modify object in for loop? React Native

I am new in react native , I want to insert new value into every object of array.

I have successfully implemented the logic according to object value. Condition is working right, I have checked by console.log() the statement working right but when I print the my final output array the new value of every object is same, value not assign different in object according to condition.

Here is the code which I am using:-

var newOffers = [];
response.data.forEach((element) => {
  for (let i = 0; i < element.frequency; i++) {
    var offer = element;
    if (offer.used == 0) {
      offer.isAvailable = "true";
      newOffers.push(offer);
    } else {
      if (offer.frequency - i <= offer.used) {
        console.log("True calling", offer.frequency - i);
        offer.isAvailable = "false";
        newOffers.push(offer);
      } else {
        console.log("False calling", offer.frequency - i);
        offer.isAvailable = "true";
        newOffers.push(offer);
      }
    }
  }
});
console.log("All offers ", newOffers);

I have assign "isAvailable" value "true" or "false" to offer object and all condition working perfectly but when I print the "newOffers" array after complete the loop process the all "isAvailable" values is "false"

What wrong with this code? can someone help me?

Upvotes: 0

Views: 275

Answers (1)

Erfan Atp
Erfan Atp

Reputation: 393

In javascript when you use = operator for the objects, it doesn't work like as you expect. You should change your code like this if you are familiar with ES6:

var offer = {...element}

or

var offer = Object.assign({}, element);

Read this

Upvotes: 1

Related Questions