Gunjan Anshul
Gunjan Anshul

Reputation: 103

Process/Calculate two objects values and generate output from them

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
}

Upvotes: 2

Views: 187

Answers (1)

hgb123
hgb123

Reputation: 14891

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/[email protected]/dist/math.min.js"></script>

Upvotes: 1

Related Questions