[英]calculate price based on price table
i want to create a price calculator FORM that print total price based on price table.我想创建一个价格计算器 FORM,它根据价格表打印总价。 but there are too many price variations.
但是价格变化太多了。
.
.
as in the image checking on by one like this:正如在图像检查中这样的:
if(type="type1" && size="22" && method="method1" && width=="150mm"){
totalPrice = 120;
}
is difficult.很难。
is there a another way to do these kind of calculation like put data into JSON array and iterate through it to get the price.有没有另一种方法可以进行此类计算,例如将数据放入 JSON 数组并遍历它以获得价格。
Create a database object and store all the data in such a format that it can be retrieved based on the input property.创建一个数据库对象并以可以根据输入属性检索的格式存储所有数据。
use this analogy:使用这个类比:
const database = {
"type1": {
"20ft": {
"method1": {
"150mm": "125$",
"200mm": "132$",
"250mm": "142$"
},
"method2": {
...
},
"method3": {
...
}
},
"21ft": {
...
}
},
"type2": {
...
}
}
// When you want to fetch the answer use call the variable like this
const answer = database?.["type1"]?.["20ft"]?.["method1"]?.["150mm"] || null;
This method is possible using array filter and map这种方法可以使用数组过滤器和映射
save as get-price.js
另存为
get-price.js
const data = [ { "type": "type1", "size": "20ft", "length": "150mm", "method": "method1", "price": "125$" }, { "type": "type1", "size": "20ft", "length": "150mm", "method": "method2", "price": "152$" }, { "type": "type1", "size": "20ft", "length": "150mm", "method": "method3", "price": "170$" }, { "type": "type1", "size": "20ft", "length": "200mm", "method": "method1", "price": "132$" }, { "type": "type1", "size": "20ft", "length": "200mm", "method": "method2", "price": "152$" }, { "type": "type1", "size": "20ft", "length": "200mm", "method": "method3", "price": "212$" }, { "type": "type1", "size": "20ft", "length": "250mm", "method": "method1", "price": "142$" }, { "type": "type1", "size": "20ft", "length": "250mm", "method": "method2", "price": "182$" }, { "type": "type1", "size": "20ft", "length": "250mm", "method": "method3", "price": "112$" } ] const getPrice = (type, size, length, method) => { return (data // filter matched condition.filter(el => { return el.type == type && el.size == size && el.length == length && el.method == method }) // map return price and first item of array.map (el => { return el.price })[0]) } console.log(getPrice('type1', '20ft', '150mm', 'method3')) console.log(getPrice('type1', '20ft', '150mm', 'method1')) console.log(getPrice('type1', '20ft', '250mm', 'method2'))
Result结果
$node get-price.js
170$
125$
182$
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.