简体   繁体   English

将本地存储项添加到 javascript 数组中

[英]Add localstorage items into a javascript array

Good Day.再会。 I am collecting product information (cart) for an e-commerce web app in local storage.我正在为本地存储中的电子商务 web 应用程序收集产品信息(购物车)。 I need to send the productId to the STRIPE api but I am having trouble.我需要将 productId 发送到 STRIPE api 但我遇到了麻烦。 The local storage variable is below本地存储变量如下

window.localStorage.getItem('products')

It outputs an array like below它输出一个如下所示的数组

[{"productId":"37", "quantity":"2"}]

The stripe API wants a format like this条带 API 想要这样的格式

var purchase = { 
  items: [{ id: 2235 }]
};

I thought I could accomplish it by this code below我想我可以通过下面的代码来完成它

var newarr = window.localStorage.getItem('products');
var purchase = {
  items: []
};
for (var i in newarr) {
  var item = newarr[i];

  purchase.items.push({
    id: item.productId
  });
}

Unfortunately, I am doing something wrong.不幸的是,我做错了什么。 Any ideas???有任何想法吗??? Arrays and objects are my weakness:( Arrays 和对象是我的弱点:(

localStorage items are always stored & retrieved as a string. localStorage项目始终作为字符串存储和检索。

You'll need to convert it into the respective object time when you read the data.读取数据时需要将其转换为相应的 object 时间。 In your case you need to read is as a JSON object.在您的情况下,您需要阅读 JSON object。 This should do the trick这应该可以解决问题

var newarr = JSON.parse(window.localStorage.getItem('products'));

If you are still not able to get it, apply JSON.stringify on the data before storing in localStorage .如果您仍然无法获得它,请在存储到localStorage之前对数据应用JSON.stringify

localStorage.getItem is string so you need to parse it with JSON.parse() localStorage.getItem是字符串,因此您需要使用JSON.parse()解析它

Here added a fiddle .这里添加了一个fiddle Hope this will be helpful希望这会有所帮助

window.localStorage.setItem('products','[{"productId":"37", "quantity":"2"}]'); 
var newarr = JSON.parse(window.localStorage.getItem('products'));
//console.log(newarr);
var purchase = {
   items: []
};
for(var i in newarr) {  

var item = newarr[i];   

purchase.items.push({ 
    "id" : item.productId
    
});
}
console.log('final array see console',purchase)

maybe try this也许试试这个

const newarr = window.localStorage.getItem('products');
const parsedAr = JSON.parse(newarr);
const purchase = {
    items: parsedAr
};

// prepare for testing...
localStorage.setItem("products", '[{"productId":"37", "quantity":"2"}, {"productId":"137", "quantity":"12"}]')
console.log(localStorage.getItem("products"))


// this is what you ask for: 

let purchase = 

  // parse string from localStorage as object that has productId property
  JSON.parse(localStorage.getItem("products")).

  // for each object create new one and make "id" from "productId"
  map(myOb => { return { "id": myOb["productId"] } });



console.log(purchase);

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

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