Reputation: 3160
I have a array of json objects in jquery . I want to duplicate a object and then replace key value in original object on the basis of if condition . but every time i replaced the value in single object then it replaced the values in both objects . I only want to replace in one i.e original I have used break and return false statements but dont work.
var index=getIndex(class_id,teacher_id);
finalJson[index]['teacher_name']='asad';
function getIndex(class_id,teacher_id){
for(var it in finalJson){
if(finalJson[it]['class'] == class_id && finalJson[it]['type'] == 'c'){
finalJson.push(finalJson[it])
return it;
}
}
}
please anybody help here is if condition . Thanks in advance.
Upvotes: 2
Views: 1191
Reputation: 68393
When you do finalJson.push(finalJson[it])
you are pushing the reference to old object again in the array. So, any operation done on one reference will be performed on the object to which new reference is pointing to. Which is why you need to create a new object using the properties of old one (using Object.create
) and then push it.
replace
finalJson.push(finalJson[it])
with (don't use this option)
finalJson.push(Object.create(finalJson[it]))
or a slower but deep-copy option
finalJson.push(JSON.parse(JSON.stringify(finalJson[it])));
Upvotes: 4
Reputation: 2961
When you copy the object to a new variable, you are creating a reference. You need to create a new object to prevent this, otherwise the changes applied to one object will apply to the other.
Upvotes: 1