I have an object
let returnObj = {
test_on_Home_Page: {
page: 'Home Page',
total_sum: -141.16874354518953,
top_url: null
},
test_on_Product_List: {
page: 'Product List',
total_sum: -147.16874354518953,
top_url: null
},
testOther_on_Home_page: {
page: 'Home Page',
total_sum: -48.16874354518953,
top_url: null
},
}
I want to calculate total_sum of Object keys by pages, like this
{
HomePage : -189.33744
ProductList : -147.168743
}
I have tried
let totalCart = 0;
for(let errorName of Object.keys(returnObj)){
if(returnObj[errorName]['page'] == "Cart"){
totalCart = returnObj[errorName]['total_sum']
}
}
But that doesn't look dynamic to me.
Can this be done with one line With something like this
let list = [];
for(let errorName of Object.keys(returnObj)){
list[returnObj[errorName]] = returnObj[errorName]['total_sum']
}
CodePudding user response:
You need to iterate values
, not keys
:
let sums = {}
for (let obj of Object.values(returnObj))
sums[obj.page] = (sums[obj.page] ?? 0) obj.total_sum
CodePudding user response:
If you want to use more of a functional aproach
const sums = {}
Object.values(returnObj).forEach(item => {
sums[item.page] = (sums[item.page] ?? 0) item.total_sum
})
Using the lodash lib:
const sums = {}
_.values(returnObj).forEach(item => {
sums[item.page] = (sums[item.page] ?? 0) item.total_sum
})
CodePudding user response:
Here's an approach using Array.prototype.reduce
on Object.values(returnObj)
:
const o = {
test_on_Home_Page: {
page: 'Home Page',
total_sum: -141.16874354518953,
top_url: null
},
test_on_Product_List: {
page: 'Product List',
total_sum: -147.16874354518953,
top_url: null
},
testOther_on_Home_page: {
page: 'Home Page',
total_sum: -48.16874354518953,
top_url: null
},
}
const sums = Object.values(o)
.reduce((a, { page: p, total_sum: s }) => ({...a, ...{ [p]: (a[p] ?? 0) s } }), {});
console.log(sums);