简体   繁体   English

使用 localStorage.getItem 获取键的第一个元素

[英]Get first element of a key using localStorage.getItem

I was reading the country of the visitor from local storage using localStorage.getItem I was reading this info directly form Google CMP.我正在使用 localStorage.getItem 从本地存储中读取访问者的国家/地区,我正在直接从 Google CMP 读取此信息。

console.log("Country code: " + localStorage.getItem('vpb-location'));
var countrycodeckeck = localStorage.getItem('vpb-location');

if (
    countrycodeckeck !== "PH" && //philippines
    countrycodeckeck !== "TH" //thailand
) {

The problem is that now Google changed the key from vpb-location to vpbg and now contains more info.问题是现在谷歌将密钥从 vpb-location 更改为 vpbg 并且现在包含更多信息。

Example:例子:

var countrycodeckeck = localStorage.vpbg;
console.log(countrycodeckeck);

{"countryCode":"PL","isEU":true,"ts":1641125302501} {"countryCode":"PL","isEU":true,"ts":1641125302501}

Can you please tell me how to modify our code to check the “countryCode” stored in the local storage?您能告诉我如何修改我们的代码以检查存储在本地存储中的“countryCode”吗?

The data in the storage key is encoded as JSON.存储密钥中的数据编码为 JSON。 To access the information you need to decode the JSON to usable JavaScript with JSON.parse() .要访问您需要使用JSON.parse()将 JSON 解码为可用的 JavaScript 的信息。

// Get the data from the storage.
const vpbg = localStorage.getItem('vpbg');

// Only proceed of there is actually data.
if (vpbg !== null) {
  // Parse the JSON to an object.
  const data = JSON.parse(vpbg);
  
  // data is now an object with properties that you can access.
  const countryCodeCheck = data.countryCode;

  if (
    countryCodeCheck !== "PH" && //philippines
    countryCodeCheck !== "TH" //thailand
  ) {
    // Do something if it checks out.
  }
}

You further append it with a dot to access those properties:你进一步 append 它用一个点来访问这些属性:
localStorage.vpbg.countryCode

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM