Вы можете l oop объектов с for(.. in ..)
const relativeWeight = {
"Composure": 0.175,
"Build": 0.128,
"Strategic": 0.096,
"Career": 0.079,
"Change": 0.062,
"Participative": 0.059,
"SelfAware": 0.055,
"Leading": 0.048,
"Taking": 0.047,
"Balance": 0.041,
"Putting": 0.041,
"Compassion": 0.039,
"Decisive": 0.037,
"Respect": 0.033,
"Quick": 0.031,
"Confront": 0.028
}
const values = {
Strategic: 1,
Decisive: 1,
Quick: 1,
Change: 1,
Leading: 1,
Confront: 1,
Build: 1,
Compassion: 1,
Putting: 1,
Respect: 1,
Taking: 1,
Composure: 1,
Balance: 1,
SelfAware: 1,
Career: 1,
Participative: 1
}
function multiplyObjects(objA, objB){
const outputObj = {};
for(prop in objA){
outputObj[prop] = objB[prop] * objA[prop];
}
return outputObj;
}
function sumArray(arr){
return arr.reduce((acc, val) => acc+val, 0);
}
console.log('functional programming version:', sumArray(Object.values(multiplyObjects(relativeWeight, values))));
// or you can only use a single loop for both multiply and add:
function operateOnObjects(objA, objB, operationFn){
const outputObj = {};
for(prop in objA){
outputObj[prop] = operationFn(objB[prop], objA[prop]);
}
return outputObj;
}
function multiplyAndAddObjects(objA, objB){
let sum = 0;
let multipliedOutput = operateOnObjects(relativeWeight, values, (a,b) => {
sum += a*b;
});
return sum;
}
console.log('single loop:', multiplyAndAddObjects(relativeWeight, values));
// to solve the precision error, multiply to ensure it is not a floating
// point number and then divide by the same afterwards
function customMultiplyAndAddObjects(objA, objB){
let sum = 0;
const sfAmount = 1000;
let multipliedOutput = operateOnObjects(relativeWeight, values, (a,b) => {
sum += a*sfAmount*b;
});
return sum / sfAmount;
}
console.log('precision fixed:', customMultiplyAndAddObjects(relativeWeight, values));
Это чище, чем для (.. of ..), который потребует от вас сначала преобразовать объект в массив, например, с помощью Object.entries (obj).