0

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?

4
  • Include a sample of response.data and what is the expected output. Commented Feb 6, 2021 at 17:00
  • 1
    So do more debugging: you have two cases where you set it to true, prove to yourself (before you prove to us) that the preconditions for those cases even apply. Because if you only see false it stands to reason that offer.used === 0 is false (don't use ==, use === unless you know exactly why you need type coercion) and that offer.frequency - i <= offer.used is false. Also, if you're using let, don't also use the legacy var, stick with let for mutables and const for immutables. Commented Feb 6, 2021 at 17:02
  • Your code could use a little refactoring, but I don't see any reason for why the thing you describe should be happening. Commented Feb 6, 2021 at 17:03
  • ok its working now I just replace this line "var offer = element;" to "let offer = { ...element };" this one Commented Feb 6, 2021 at 17:07

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.