Jquery将Json保存到两个变量然后只拼接一个
我想将 Json 保存到两个变量中,以便我可以操作其中一个,并在需要将数据恢复和重置为原始数据时保存原始数据。
Json 有 4 项。我有两个变量,它们最初共享相同的数据,我可以看到它们正在控制台中工作。然而,当我拼接“当前”变量时,“原始”变量也会以某种方式被拼接。我只想对当前变量进行拼接、弹出和推送。
我的目标是拥有两个对象并且只操纵其中一个。我无法使用 cookie 或服务器。
<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>
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>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要复制 JSON,否则
jsonOriginal
和jsonCurrent
只是对同一对象的引用。使用而不是
当您想要将 jsonOriginal 复制回来时,使用相同的方法将其复制回来可能是一个好主意。
You need to make a copy of the JSON, otherwise
jsonOriginal
andjsonCurrent
are just references to the same object. Useinstead of
It would probably be a good idea to use the same method to copy jsonOriginal back when you want it back.