2

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
}
Jan Schultke
  • 17,446
  • 6
  • 47
  • 96
Gunjan Anshul
  • 103
  • 1
  • 7

1 Answers1

1

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>
hgb123
  • 13,869
  • 3
  • 20
  • 38