json 按价目表计价

rhfm7lfc  于 2022-12-20  发布在  其他
关注(0)|答案(2)|浏览(100)

我想创建一个基于价格表打印总价价格计算器表单。2但有太多的价格变化。



像这样的图像检查:

if(type="type1" && size="22" && method="method1" && width=="150mm"){
totalPrice = 120;
}

是困难的。
有没有其他的方法来做这种计算,比如把数据放入JSON数组,然后迭代它来得到价格。
this codepen Example

dgsult0t

dgsult0t1#

创建一个数据库对象,并以可基于输入属性检索的格式存储所有数据。
用这个比喻:

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;
qltillow

qltillow2#

此方法可以使用数组过滤器和Map
保存为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'))

结果

$node get-price.js

170$
125$
182$

相关问题