Kevin
Kevin

Reputation: 653

How to add new key and value to array using angular.js?

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

Upvotes: 0

Views: 64

Answers (2)

Suneet Bansal
Suneet Bansal

Reputation: 2702

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

Upvotes: 0

T J
T J

Reputation: 43156

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

Upvotes: 2

Related Questions