【问题标题】:Process/Calculate two objects values and generate output from them处理/计算两个对象值并从中生成输出
【发布时间】:2020-08-24 05:18:30
【问题描述】:

我有两个对象 - 一个包含公式,另一个数组对象包含值。 我想加入俱乐部并计算如下所示的输出。

对象-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
}

【问题讨论】:

  • 你的问题是什么?这里的数学很简单......

标签: javascript node.js mathjs


【解决方案1】:

您可以考虑parsecompile 表达式(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>

【讨论】:

    猜你喜欢
    • 2013-08-27
    • 1970-01-01
    • 2014-04-21
    • 2011-06-26
    • 2012-05-15
    • 2019-06-28
    • 2018-03-09
    • 1970-01-01
    • 2021-01-13
    相关资源
    最近更新 更多