我有一个类型为[[{name:'xxx',价格:'555',数量:'2'},{...}]的对象,等等。 我上了课
getCartItems() {
let items = localStorage.getItem('item');
items = JSON.parse(items);
return items;
}
我在哪里得到这个数组。 现在我正在获取数组的索引,例如0,它应该从对象中删除第一个数组。 但是当我做.remove或其他操作时,它不起作用。 this.getCartItems()[index] .remove或其他方法无效。你能帮我吗?
答案 0 :(得分:0)
我的猜测是,您在解析对象后会对它进行突变,而您再也不会保存它。
您必须将变异的对象保存在localStorage中,以使持久性项的删除成为可能。
看下面的例子:
const localStorage = {
items: {
item: JSON.stringify([{
name: 'xxx',
price: '555',
quantity: '2',
}, {
name: 'yyy',
price: '666',
quantity: '5',
}, {
name: 'zzz',
price: '777',
quantity: '6',
}]),
},
getItem: str => localStorage.items[str],
setItem: (str, value) => {
localStorage.items[str] = value;
},
};
function getCartItems() {
const items = localStorage.getItem('item');
const parsedItems = JSON.parse(items);
// We remove the first element
const item = parsedItems.splice(0, 1);
// We save the value
localStorage.setItem('item', JSON.stringify(parsedItems));
return item;
}
console.log('First call ---');
console.log(getCartItems());
console.log('');
console.log('Second call ---');
console.log(getCartItems());
console.log('');
console.log('Third call ---');
console.log(getCartItems());
答案 1 :(得分:0)
使用filter
获取必填项。在以下更新中将没有较早的0索引项。现在,如果需要,您可能希望再次在localStorage中设置updated
数组。
const items = getCartItems();
const indexToRemove = 0;
const updated = items.filter((,index) => index !== indexToRemove);
答案 2 :(得分:0)
您可以使用数组方法filter
从数组中删除对象。看起来可能像这样:
getCartItems() {
let items = localStorage.getItem('item');
items = JSON.parse(items);
return items;
}
removeCart(){
return id; // the id that you will have from your a tag
}
const updatedItems = this.getCartItems().filter((item,index) => index !== this.removeCart()); // in updated items you will find your filtered out array of object