Last active
March 13, 2017 22:32
-
-
Save aabril/1cd837705aefbc67e88a4efc452ff089 to your computer and use it in GitHub Desktop.
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
| var flatten = function(data) { | |
| var result = {}; | |
| function recurse (cur, prop) { | |
| if (Object(cur) !== cur) { | |
| result[prop] = cur; | |
| } else if (Array.isArray(cur)) { | |
| for(var i=0, l=cur.length; i<l; i++) | |
| recurse(cur[i], prop ? prop+"."+i : ""+i); | |
| if (l == 0) | |
| result[prop] = []; | |
| } else { | |
| var isEmpty = true; | |
| for (var p in cur) { | |
| isEmpty = false; | |
| recurse(cur[p], prop ? prop+"."+p : p); | |
| } | |
| if (isEmpty) | |
| result[prop] = {}; | |
| } | |
| } | |
| recurse(data, ""); | |
| return result; | |
| } | |
| var flattenObject = flatten(tree); | |
| var total = 0; | |
| for (var prop in flattenObject) { | |
| if(prop.indexOf('precio_linea')>0){ | |
| total += parseFloat(flattenObject[prop]); | |
| } | |
| } | |
| console.log(total.toFixed(2)); |
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
| ➜ a node app2.js | |
| { '0.id': '201724171830', | |
| '0.parent': '', | |
| '0.piezas': ' 10', | |
| '0.precio_linea': '22.50', | |
| '0.children.0.id': '20172515426', | |
| '0.children.0.parent': '201724171830', | |
| '0.children.0.piezas': ' 10', | |
| '0.children.0.precio_linea': '50.50', | |
| '0.children.0.children.0.id': '201725123623', | |
| '0.children.0.children.0.parent': '20172515426', | |
| '0.children.0.children.0.piezas': ' 10', | |
| '0.children.0.children.0.precio_linea': '34.21', | |
| '0.children.0.children.1.id': '201724171631', | |
| '0.children.0.children.1.parent': '20172515426', | |
| '0.children.0.children.1.piezas': ' 10', | |
| '0.children.0.children.1.precio_linea': '34.21', | |
| '0.children.0.children.2.id': '20172515548', | |
| '0.children.0.children.2.parent': '20172515426', | |
| '0.children.0.children.2.piezas': ' 10', | |
| '0.children.0.children.2.precio_linea': '34.21', | |
| '1.id': '201724194033', | |
| '1.parent': '', | |
| '1.piezas': ' 10', | |
| '1.precio_linea': '34.21' } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment