export const addNabuaItem = (item = [], count = 0, next = f => f) => {
let nabua = [];
if (typeof window !== 'undefined') {
if (localStorage.getItem('nabua')) { //If it has cart in local storage then ...
//NOTE to convert json to object
// get product from local storage
nabua = JSON.parse(localStorage.getItem('nabua'));
}
//NOTE store it as an Array of Object
nabua.push({
...item,
count: 1 // NOTE intitial count after item was added by a user is one
});
// remove duplicates
// build an Array from new Set and turn it back into array using Array.from
// so that later we can re-map it
// new set will only allow unique values in it
// so pass the ids of each object/product
// If the loop tries to add the same value again, it'll get ignored
// ...with the array of ids we got on when first map() was used
// run map() on it again and return the actual product from the cart
nabua = Array.from(new Set(nabua.map(p => p._id))).map(id => {
return nabua.find(p => p._id === id);
});
localStorage.setItem('nabua', JSON.stringify(nabua));
next();
}
};
这是我用于将产品添加到购物车的代码(存储在本地存储中)。我只想添加产品的特定属性,例如名称,价格和说明,因为我不想在本地存储中存储不必要的属性。我怎样才能做到这一点 ?
下面是我的本地存储控制台,其中包含产品对象, enter image description here
答案 0 :(得分:0)
在分配给nabua
时只需添加另一个地图即可,它看起来像这样:
nabua = Array.from(new Set(nabua.map(p => p._id))).map(id => {
return nabua.find(p => p._id === id);
})
.map(item => ({
field1: item.field1,
field2: item.field2
}));
将field1
/ field2
设置为您喜欢的任何字段。因此,如果您想要名称,描述和价格,它可能看起来像这样
.map(item => ({
name: item.name,
description: item.description,
price: item.price
}));