I have an Object of Arrays like this and I want to combine them(add values to every key )
It's possible to give to every array key: "state" and value: parseFloat(value) or how i can do it?
-
Use for loop or reduce to add up the values.evolutionxbox– evolutionxbox2021年06月14日 11:04:19 +00:00Commented Jun 14, 2021 at 11:04
-
Does this answer your question? Sum values of objects in arrayevolutionxbox– evolutionxbox2021年06月14日 11:04:39 +00:00Commented Jun 14, 2021 at 11:04
-
Isn't the title should be an array of objects?ikhvjs– ikhvjs2021年06月14日 11:08:43 +00:00Commented Jun 14, 2021 at 11:08
-
2Can you please update your question with the expected output and the attempt(s) you made of solving the problem? This way we can help you understand the issue betterStackByMe– StackByMe2021年06月14日 11:11:58 +00:00Commented Jun 14, 2021 at 11:11
1 Answer 1
You can save yourself some typing, and provide some future-proofing in case you later need to handle a different set of territories, by getting the keys from the object itself, and then iterating over those keys:
let val = {};
val = filteredMiles.reduce(
function (previousValue, currentValue) {
const keys=Object.keys(previousValue);
const result={};
keys.forEach(key=>{
result[key]= parseFloat(previousValue[key]))
+parseFloat(currentvalue[key])
})
return result
};
});
console.log(val);
answered Jun 14, 2021 at 12:00
ProfDFrancis
9,4091 gold badge23 silver badges33 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
lang-js