javascript - inserting into json array in js/angularjs -
i have json array
var testarr=[{name:"name1",age:20},{name:"name1",age:20},{name:"name1",age:20}]
how insert item "uid" testarr looks this
var testarr=[{name:"name1",age:20,uid:1},{name:"name1",age:20,uid:2},{name:"name1",age:20,uid:3}]
i have tried following js code seems add @ end
var testarr=[{name:"name1",age:20},{name:"name1",age:20},{name:"name1",age:20}]; var loopcycle = (testarr.length); for(i=0; < loopcycle ; i++){ testarr.push({uid:i+1}) } console.log(testarr)
thanks
your problem here:
testarr.push({uid:i+1})
for each element in array, creating new element ({uid:i+1}
). need access json object , create new property. try this:
var testarr=[{name:"name1",age:20},{name:"name1",age:20},{name:"name1",age:20}]; var loopcycle = (testarr.length); for(i=0; < loopcycle ; i++){ testarr[i]['uid'] = i+1; } console.log(testarr);
if want using angular way, try this:
angular.foreach(testarr, function (x,idx) { x.uid = idx+1; });
Comments
Post a Comment