Kevin Kevin - 6 months ago 13
AngularJS Question

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

T J T J
Answer

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