I want to save Json into two variables so that I can manipulate one, and save the original when I need to restore and reset the data to the original.
The Json has 4 items. I have my two variables, they both share the same data initially, and I can see they are working in the console. However, when I splice the “Current” var the “Original” var somehow also gets spliced too. I just want to splice, pop, and push on the Current var.
My goal is to have two objects and only to manipulate one. I can’t use cookies or the server.
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.pack.js"></script>
<script type="text/javascript">
var jsonOriginal;//used for the original json object
var jsonCurrent;//used for the filtered json object that gets manipulated
$.ajax({
url: "sources/json.txt",
dataType: 'json',
success: (function(json)
{
//save the JSON into two variables for later use
jsonOriginal = json;
jsonCurrent= json;
doSomething();
})
});
function doSomething(){
console.log(jsonOriginal);//has 4 items
console.log(jsonCurrent);//has 4 items
//Splice ONLY CURRENT
jsonCurrent.items.splice(2, 3);//remove 2 items from jsonCurrent
console.log(jsonOriginal);//has 2 items -- WHAT????
console.log(jsonCurrent);//has 2 items as expected
//reset Current to the Original
jsonCurrent=jsonOriginal;//should go back to the 4 items
}
</script>
You need to make a copy of the JSON, otherwise
jsonOriginalandjsonCurrentare just references to the same object. Usevar jsonOriginal = jQuery.extend(true, {}, json);instead of
It would probably be a good idea to use the same method to copy jsonOriginal back when you want it back.