3

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

1
  • testArr[i]. you are missing the index Commented Feb 5, 2016 at 19:56

1 Answer 1

4

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; });
Sign up to request clarification or add additional context in comments.

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.