I have two objects - one containing formulas and other array object contains values. I want to club and do calculate output shown below.
Object-1
{
SI : (PxTxR)/100,
ratio: P1/P2
}
Object-2
[
{
P1:34053,
P2:45506
},
{
P:3403,
T:3,
R:7.35
P1:34053,
P2:45506
}
]
Result :
{
SI:750.36,
ratio:0.74
}
You could regard to parse
, compile
expression ( obj1
) and evaluate
with scope (element of obj2
)
Below is a worked solution
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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.