Created
September 13, 2017 20:34
-
-
Save Woodsphreaker/cd8abf17f82b46bfab2dec6db30ce4bb to your computer and use it in GitHub Desktop.
flattenObjectArray
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const data = [ | |
{ "itemSelected": "item1", "data": "2017-09-12", "descricaoPrestacao": "desc1 item1", "valor": 1 }, | |
{ "descricaoPrestacao": "desc2 item2", "valor": 2, "itemSelected": "item2", "data": "2017-09-12" }, | |
{ "descricaoPrestacao": "desc3 item3", "valor": 3, "itemSelected": "itemMIL", "data": "2017-09-12" }, | |
{ "descricaoPrestacao": "desc2 item1", "valor": 1, "itemSelected": "item1", "data": "2017-09-12" }, | |
{ "descricaoPrestacao": "desc2 item2", "valor": 2, "itemSelected": "item2", "data": "2017-09-12" } | |
] | |
const flatten = (obj) => { | |
return obj.reduce((acc, el) => { | |
acc[el.itemSelected] | |
? acc[el.itemSelected] += el.valor | |
: acc[el.itemSelected] = el.valor | |
return acc | |
}, {}) | |
} | |
const makeArray = (obj) => { | |
return Object.keys(obj) | |
.reduce((acc, el) => | |
acc.concat({ | |
[el]: obj[el] | |
}), []) | |
} | |
console.log(makeArray(flatten(data))) // [ { item1: 2 }, { item2: 4 }, { itemMIL: 3 } ] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment