typescript 本地存储:从每个键获取每个值

6xfqseft  于 2023-05-08  发布在  TypeScript
关注(0)|答案(8)|浏览(227)

我想遍历每个键并从每个键中获取name值。这就是我的本地存储的样子。
key:3值:{“name”:“Kevin”,“country”:“加拿大”,“about”:“Test”,“image”:“"}
key:4值:{“name”:“Homer”,“country”:“加拿大”,“about”:“Test”,“image”:“"}
我想得到这两个名字并把它们添加到数组中。我尝试了这个方法:

for(var key in localStorage){
   let user = JSON.parse(localStorage.getItem(key));
   this.users.push(user);
}

我得到的错误是:
语法错误:JSON中位置1处的意外标记e

lxkprmvk

lxkprmvk1#

var keys = Object.keys(localStorage);
 keys.forEach(key=>{
  var json_str =localStorage.getItem(key)
   try {
       var abc = JSON.parse(json_str);
       this.user = abc;
    } catch (e) {
    console.log(e)
   }
})
fae0ux8s

fae0ux8s2#

当你说I want to getboth of these names时,我不明白,但无论哪种方式,你都可以这样做:

var keys = Object.keys(localStorage);
for(var i=0;i<keys.length;i++){
    var key = keys[i];
    console.log(key, localStorage[key]);
    //store here "both names" where you want them
    //you can also access each element with localStorage[key].name, localStorage[key].country, etc.
}
b4qexyjb

b4qexyjb3#

这是对Robert's answer的改进。
只需枚举localStorage中具有字符串name属性的所有值(键本身无关紧要)。然后返回该数组。
根据您自己的答案,您可能会遇到不一致的可变状态,因为将临时变量移动到示例作用域不会影响您的情况。

function getUsers() {
  return Object.values(localStorage)
    .map(json => {
      try {
        return JSON.parse(json);
      }
      catch (e) {
        return undefined;
      }
    })
    .filter((user?: any): user is {name: string} => user && typeof user.name === 'string');
}

const users = getUsers();
hs1rzwqc

hs1rzwqc4#

你可以考虑使用我的库ngx-store来处理localStorage,sessionStorage,cookie和更多的Angular。为了实现你想要的,你将能够在存储中存储整个数组,或者只是使用像下面这样的代码与你当前的数据结构:

import { LocalStorageService } from 'ngx-store';

export class Example {
  public users: Array<any> = [];

  constructor(public localStorageService: LocalStorageService) {
    this.localStorageService.utility.forEach((value, key) => this.users.push(value));
  }
}

真的,就可以这么简单;)

qzlgjiam

qzlgjiam5#

你可以使用方法hasOwnProperty('propertyName')来检查对象中的name是否可用。然后执行所需的操作。

let localStorage = {
    "key1": {"name":"Kevin","country":"Canada","about":"Test","image":""},
    "key2": {"name":"Homer","country":"Canada","about":"Test","image":""}
}
for(let key of Object.keys(localStorage)){
    if(localStorage[key].hasOwnProperty('name')){
        console.log(localStorage[key]['name']);
    }
}
d4so4syb

d4so4syb6#

使用spread运算符获取所有localstorage作为新对象

const items = { ...localStorage };
console.log(items);
vhipe2zx

vhipe2zx7#

const  allItems = []
    const keys = Object.keys(window.localStorage);  // all keys

    keys.forEach(key=> {
      const item = JSON.parse(localStorage.getItem(key) + '');  //item with type Object
      allItems.push(item);
    });
    console.log(allItems) // arry of object
huwehgph

huwehgph8#

我设法解决了这个问题,这是一个简单的错误,总是在循环中初始化一个新的let user
我移走了user,其余的代码可以工作。

user: any;

  getUsers():void{
    for(var key in localStorage){
      this.user = JSON.parse(localStorage.getItem(key));
      this.users.push(this.user);
    }
  }

相关问题