Process/Calculate 两个对象值并从中生成输出
Process/Calculate two objects values and generate output from them
我有两个对象 - 一个包含公式,另一个数组对象包含值。
我想俱乐部并计算如下所示的输出。
对象-1
{
SI : (PxTxR)/100,
ratio: P1/P2
}
对象 2
[
{
P1:34053,
P2:45506
},
{
P:3403,
T:3,
R:7.35
P1:34053,
P2:45506
}
]
结果:
{
SI:750.36,
ratio:0.74
}
您可以考虑 parse
、compile
表达式 (obj1
) 和 evaluate
范围(obj2
的元素)
下面是一个可行的解决方案
const obj1 = { SI: `(P*T*R)/100`, ratio: `P1/P2` }
const obj2 = [
{ P1: 34053, P2: 45506 },
{ P: 3403, T: 3, R: 7.35, P1: 34053, P2: 45506 },
]
const nodeObj1 = Object.entries(obj1).map(([expName, exp]) => [
expName,
math.parse(exp).compile(),
])
const res = obj2.map((obj) => {
return Object.fromEntries(
nodeObj1.map(([expName, compiledExp]) => {
try {
return [expName, compiledExp.evaluate(obj)]
} catch (err) {
return [expName, undefined]
}
})
)
})
console.log(res)
<script src="https://unpkg.com/mathjs@7.1.0/dist/math.min.js"></script>
我有两个对象 - 一个包含公式,另一个数组对象包含值。 我想俱乐部并计算如下所示的输出。
对象-1
{
SI : (PxTxR)/100,
ratio: P1/P2
}
对象 2
[
{
P1:34053,
P2:45506
},
{
P:3403,
T:3,
R:7.35
P1:34053,
P2:45506
}
]
结果:
{
SI:750.36,
ratio:0.74
}
您可以考虑 parse
、compile
表达式 (obj1
) 和 evaluate
范围(obj2
的元素)
下面是一个可行的解决方案
const obj1 = { SI: `(P*T*R)/100`, ratio: `P1/P2` }
const obj2 = [
{ P1: 34053, P2: 45506 },
{ P: 3403, T: 3, R: 7.35, P1: 34053, P2: 45506 },
]
const nodeObj1 = Object.entries(obj1).map(([expName, exp]) => [
expName,
math.parse(exp).compile(),
])
const res = obj2.map((obj) => {
return Object.fromEntries(
nodeObj1.map(([expName, compiledExp]) => {
try {
return [expName, compiledExp.evaluate(obj)]
} catch (err) {
return [expName, undefined]
}
})
)
})
console.log(res)
<script src="https://unpkg.com/mathjs@7.1.0/dist/math.min.js"></script>