简体   繁体   中英

Add localstorage items into a javascript array

Good Day. I am collecting product information (cart) for an e-commerce web app in local storage. I need to send the productId to the STRIPE api but I am having trouble. 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

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:(

localStorage items are always stored & retrieved as a string.

You'll need to convert it into the respective object time when you read the data. In your case you need to read is as a 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.getItem is string so you need to parse it with JSON.parse()

Here added a 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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