阵列中的localstorage更新属性

localstorage update property in array

本文关键字:更新 属性 localstorage 阵列      更新时间:2023-09-27

我正在尝试更新本地存储中的一个属性。我不想把整件事循环一遍并重新设置。这可能吗?

    var aR = [
    { "id": 1, "width": 500 },
    { "id": 2, "width": 400 }
]
localStorage.setItem('test', JSON.stringify(aR));
//  need to update property
localStorage['test'][1]['width'] = '720';

您可以执行与stringify相反的操作,JSON.parse()

    var arrayString = localStorage.getItem('test');
    var a = JSON.parse(arrayString);
    a[1]['width'] = '720';
// and do the same thing, stringify and store it back to local storage

希望这有帮助:)