javascript - 根据购买的产品数量更新 JSON 值
问题描述
我有一个 javascript 购物车,它链接到一个调用产品数据的 .json api。该对象被命名为“products”,每个产品都有一个“countInStock”属性和一个值。
是否可以创建一个函数,在用户单击按钮后更新(根据购买的物品减少)相关产品的 .json 文件的“countInStock”属性?它可能是在购物车中购买的多种产品或单个产品。
这是当前用于购物车的代码:
import { parseRequestUrl, rerender } from '../utils';
import { getProduct } from '../api';
import { getCartItems, setCartItems } from '../localStorage';
const addToCart = (item, forceUpdate = false) => {
let cartItems = getCartItems();
const existItem = cartItems.find((x) => x.product === item.product);
if (existItem) {
if (forceUpdate) {
cartItems = cartItems.map((x) =>
x.product === existItem.product ? item : x
);
}
} else {
cartItems = [...cartItems, item];
}
setCartItems(cartItems);
if (forceUpdate) {
rerender(CartScreen);
}
};
const removeFromCart = (id) => {
setCartItems(getCartItems().filter((x) => x.product !== id));
if (id === parseRequestUrl().id) {
document.location.hash = '/cart';
} else {
rerender(CartScreen);
}
};
const CartScreen = {
after_render: () => {
const qtySelects = document.getElementsByClassName('qty-select');
Array.from(qtySelects).forEach((qtySelect) => {
qtySelect.addEventListener('change', (e) => {
const item = getCartItems().find((x) => x.product === qtySelect.id);
addToCart({ ...item, qty: Number(e.target.value) }, true);
});
});
const deleteButtons = document.getElementsByClassName('delete-button');
Array.from(deleteButtons).forEach((deleteButton) => {
deleteButton.addEventListener('click', () => {
removeFromCart(deleteButton.id);
});
});
document.getElementById('checkout-button').addEventListener('click', () => {
document.location.hash = '/signin';
});
},
render: async () => {
const request = parseRequestUrl();
if (request.id) {
const product = await getProduct(request.id);
addToCart({
product: product._id,
name: product.name,
image: product.image,
price: product.price,
countInStock: product.countInStock,
qty: 1,
});
}
const cartItems = getCartItems();
return `
<div class="content cart">
<div class="cart-list">
<ul class="cart-list-container">
<li>
<h3>Shopping Cart</h3>
<div>Price</div>
</li>
${
cartItems.length === 0
? '<div>Cart is empty. <a href="/#/">Go Shopping</a>'
: cartItems
.map(
(item) => `
<li>
<div class="cart-image">
<img src="${item.image}" alt="${item.name}" />
</div>
<div class="cart-name">
<div>
<a href="/#/product/${item.product}">
${item.name}
</a>
</div>
<div>
Qty:
<select class="qty-select" id="${item.product}">
${[...Array(item.countInStock).keys()].map((x) =>
item.qty === x + 1
? `<option selected value="${x + 1}">${x + 1}</option>`
: `<option value="${x + 1}">${x + 1}</option>`
)}
</select>
<button type="button" class="delete-button" id="${
item.product
}">
Delete
</button>
</div>
</div>
<div class="cart-price">
$${item.price}
</div>
</li>
`
)
.join('\n')
}
</ul>
</div>
<div class="cart-action">
<h3>
Subtotal (${cartItems.reduce((a, c) => a + c.qty, 0)} items)
:
$${cartItems.reduce((a, c) => a + c.price * c.qty, 0)}
</h3>
<button id="checkout-button" class="primary fw">
Proceed to Checkout
</button>
</div>
</div>
`;
},
};
export default CartScreen;
只是一些 JSON 代码:
module.exports = {
products: [
{
_id: '1',
name: 'Intel Core i5 11600k',
category: 'cpu',
image: '/images/intel i5.jpg',
price: 399.99,
brand: 'Intel',
countInStock: 6,
},
{
_id: '2',
name: 'Intel Core i7 11700k',
category: 'cpu',
image: '/images/intel i7.jpg',
price: 399.99,
brand: 'Intel',
countInStock: 13,
},
{
_id: '3',
name: 'Intel Core i9 11900k',
category: 'cpu',
image: '/images/intel i9.jpg',
price: 549.99,
brand: 'Intel',
countInStock: 10,
},
解决方案
听起来您只需要在您的购物车或库存对象上添加一个 getter / setter。这是一个可能会有所帮助的基本示例,尽管有点做作。如果这是您的平台,您可能想阅读 node.js 中的 JSON 要求,或者如果您有一些 JSON 作为字符串,则只需阅读 JSON.parse,但基本上重要的是您将 JSON 放入适当的对象中,这样您就可以获得或设置库存的价值(或与此相关的任何其他属性)。然后你可以制定一个函数来更新该道具,或者直接在对象本身上,或者如果你想去那里,甚至可能以不可变的方式。基本上,有几种方法可以实现类似的东西,而且它们都不一定是错误或正确的。
const pathToJSON = './foo/bar.json';
const inventory = { stock: 42 } || require(pathToJSON);
const inventoryObject = Object(inventory);
inventoryObject.increase = function(i) {
this.stock = (this.stock + i);
}
console.log(inventory.stock); // 42
inventory.increase(2)
console.log(inventory); // 44
如果您想自己玩弄它,请加上小提琴https://jsfiddle.net/bqajok8s/
推荐阅读
- arrays - 在 VB.NET 的一个消息框中显示数组
- gnuradio - 如何从 arduino 的输出端口读取到我的 GnuRadio 块?
- mysql - SQL:获取两个条件的最后记录
- python - python / ortools / cpsolver - 如果z在x和y之间,a = b
- javascript - 如何修复代码,以便仅针对点击的国家/地区显示附加卡?
- javascript - 如何使用 javascript/jquery 验证 pkcs#7 格式的签名消息
- python - 如何循环遍历熊猫数据框中列中的每一行
- python - BeautifulSoup 和 Selenium 抓取网页,汤不反映更新的 HTML
- javascript - 阻止模态内容默认打开
- mysql - Redis 连接到 my-redis:6379 失败 - 运行种子时 getaddrinfo ENOTFOUND