我有一个本地存储器,它存储一些数据。我正在尝试使用localStorage.getItem('id');在组件中获取数据,但它是未定义的。问题是,localStorage正在以一种奇怪的格式存储id。它像abcabcabc.id一样存储,现在localStorage中有多个这样的参数,对于每个登录的用户,字符串abcabcabc都会发生变化。我如何才能得到id值。我可以比较字符串或其他东西来获得值吗?比如,如果它包含字符串,.id只读取该值?如果是,你能解释如何实现这一目标吗?
地方储存:
abcabcabc.username.id = sdfsdfsdfs
abcabcabc.username.refreshToken = sdfsdfs
abcabcabc.username.accessToken = ertsdffdg发布于 2020-11-18 08:34:41
由于您不知道存储在localStorage中的确切密钥,所以请获取所有密钥,然后迭代。接下来,匹配您所知道的i.id键的一部分,如下所示:
// fetch all key-value pairs from local storage
const localStorageKeys = { ...localStorage };
// iterate over them
for (const index in localStorageKeys) {
// see if key contains id
if (index.includes('id')) {
// fetch value for corresponding key
console.log(localStorageKeys[index]);
}
}发布于 2020-11-18 08:11:01
localStorage将数据设置为键值对的映射,因此:
var id = {key:"id", value:"sdfsdfsdfs"}
//JSON.stringify converts the JavaScript object id into a string
localStorage.setItem('id', JSON.stringify(id));现在您可以通过以下方法获得数据:
var getTheId = localStorage.getItem('id');
//you can use JSON.parse() if you need to print it
console.log('getTheId: ', JSON.parse(getTheId));通常是这样做的,但由于我不知道您是如何设置数据的,所以您可以通过以下方法获得数据:
var x = localStorage.getItem(id);//normally getting your id
//parse it
var st = JSON.parse(x);
var ids = [];
while(st.includes(id)){
//this is to only get the abcabacabc
var newId = st.substring(0,9);
ids.push(newId);
}
console.log(ids);https://stackoverflow.com/questions/64888291
复制相似问题