关于javascript:如何处理

How to process & calculate - two array objects without For Loop

我有两个对象,我想在不使用 for 循环的情况下处理它们并得到结果。

key 取自 obj1 "keyname"

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
const obj1 = [{
    _id: 5 f467650890a7444d8d9ea5b,
    keyname: 'fTime',
    PTag: '(FaultHrs*360)+(FaultMins*60)+FaultSecs',
    __v: 0
  },
  {
    _id: 5 f467650890a7444d8d9ea5b,
    keyname: 'rTime',
    PTag: '(RunHrs*360)+(RunMins*60)+RunSecs',
    __v: 0
  }
]
const obj2 = {
  FaultHrs: 2,
  FaultMins: 0,
  FaultSecs: 49,
  RunHrs: 1,
  RunMins: 0,
  RunSecs: 0,

}

Result: {
  fTime: 769,
  rTime: 360
}


注意:这使用了可能很危险的 eval 函数。仅当您确定 PTag 是安全表达式时才使用它。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
const obj1 = [{ _id: '5 f467650890a7444d8d9ea5b', keyname: 'fTime',
  PTag: '(FaultHrs*360)+(FaultMins*60)+FaultSecs',    __v: 0 },
  { _id: '5 f467650890a7444d8d9ea5b', keyname: 'rTime',
  PTag: '(RunHrs*360)+(RunMins*60)+RunSecs', __v: 0 }
]
const obj2 = { FaultHrs: 2, FaultMins: 0, FaultSecs: 49, RunHrs: 1, RunMins: 0, RunSecs: 0,}

const res = obj1.reduce((res, k) => {
  // find out parameters in formula
  const matches = k.PTag.match(/[a-zA-Z]+/g);

  // substitute them with numbers
  const newTag = matches.reduce((tag, m) => tag.replace(m, obj2[m] || 0), k.PTag);

  // calculate result
  res[k.keyname] = eval(newTag);

  return res;
}, {});

console.log(res)

输出:

1
{fTime: 769, rTime: 360}