0

I have 3 object in array, for the first object i want to add ifContrbtd:false and for remaining 2 objects i want to add ifContrbtd:true. I have tried like following but it added ifContrbtd:true to 2nd and 3rd object, nothing is added to first object.

for (var key in res.result) {
    var ifContributed = false;
    if(res.result[key].newField != undefined){
        ifContributed = true;
        res.result[key]['ifContrbtd']=ifContributed;
    }               
}
0

2 Answers 2

2

You should move the assignment outside the if condition so that ifContributed = false is assigned for objects having newField. Right now nothing will be assined if it is defined:

for (var key in res.result) {
  var ifContributed = false;
  if (res.result[key].newField != undefined) {
    ifContributed = true;
  }
  res.result[key]['ifContrbtd'] = ifContributed;
}
Sign up to request clarification or add additional context in comments.

Comments

0

You have to put assign value to res.result[key]['ifContrbtd'] after the if statement not inside it.

Just below 3 lines will solve your issue:

for (var key in res.result) {
    var ifContributed = (res.result[key].newField != undefined);
    res.result[key]['ifContrbtd'] = ifContributed;
}

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.