如何在本地存储中更新JSON值 [英] How to update json value in localstorage

查看:203
本文介绍了如何在本地存储中更新JSON值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我将数组进行了字符串化处理,并保存在了'persons'键下的localStorage中.

So I have an array stringify'ed and saved in my localStorage under 'persons' key.

arr = [{"name":"a", "age": 1, "sport":"football"},
{"name":"b", "age": 2, "sport":"volley"},
{"name":"c", "age": 3, "sport":"basket"}];
localStorage.setItem('persons', JSON.stringify(arr));

当我需要更新名称为x的人的年龄(假设输入内容为名称为b的人)时,我的方法是获取并解析我的localStorage密钥:

When I need to update age for person with name x (lets say the input is person with name b), my approach is to get and parse my localStorage key:

var persons = JSON.parse(localStorage.persons);

然后我进行一个for循环,遍历对象并找到名称为b的对象:

Then I make a for loop to loop through the objects and find object with name b:

for (var i = 0; i < persons.length; i++) {
   if(inputName === persons[i].name){
       persons[i].age += 2
       localStorage.setItem("persons", JSON.stringify(aCustomers[i].age));
   }
}

这似乎不起作用. 我在循环中找到了我的匹配项,但是我不知道如何在不覆盖和销毁json对象的情况下,将年龄增加2年并在我的localStorage.persons中更新该值.

This doesnt seem to work. I've found my match in the loop, but I dont know how to add 2 years to the age and update that value in my localStorage.persons without overwriting and destroying the json objects.

推荐答案

您需要像最初那样重新设置对象,现在您只存储一个数字,而不是对象.

You need to set the object back again like you did originally, right now you are storing only a number, not the object.

var persons = JSON.parse(localStorage.persons);
for (var i = 0; i < persons.length; i++) {
   if(inputName === persons[i].name){  //look for match with name
       persons[i].age += 2;  //add two
       break;  //exit loop since you found the person
   }
}
localStorage.setItem("persons", JSON.stringify(persons));  //put the object back

这篇关于如何在本地存储中更新JSON值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆