I want to process two objects.
obj1 array object having formulas.
obj2 having values. I want to process/calculate both objects to get result such that key present in obj1 becomes actual key in output and value get processed with formula. Did it with EVAL but don't want to use eval it.
Please suggest any other method to do the same.
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)