user3589690
user3589690

Reputation: 120

inserting into json array in js/angularjs

i have a json array

var testArr=[{name:"name1",age:20},{name:"name1",age:20},{name:"name1",age:20}]  

how do i insert an item "Uid" into the testArr so that it looks like this

var testArr=[{name:"name1",age:20,uid:1},{name:"name1",age:20,uid:2},{name:"name1",age:20,uid:3}] 

I have tried the following JS code but it seems to add it at the end

var testArr=[{name:"name1",age:20},{name:"name1",age:20},{name:"name1",age:20}];  
var loopCycle = (testArr.length);  
for(i=0; i < loopCycle ; i++){  
testArr.push({uID:i+1})
}    
console.log(testArr)

Thanks

Upvotes: 3

Views: 37

Answers (1)

Javier Conde
Javier Conde

Reputation: 2593

Your problem is here:

testArr.push({uID:i+1})

For each element in the array, you are creating a new element ({uID:i+1}). You need to access the JSON object and create a 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; i < loopCycle ; i++){  
  testArr[i]['uid'] = i+1;
}    
console.log(testArr);

If you want to do it using the angular way, try this:

angular.forEach(testArr, function (x,idx) { x.uid = idx+1; });

Upvotes: 4

Related Questions