javascript - Convert recursive array object to flat array object -


i'm looking way convert array of recursive objects flat array of objects make easier work with.

[   {     "name": "bill",     "car": "jaguar",     "age": 30,     "profiles": [       {         "name": "stacey",         "car": "lambo",         "age": 23,         "profiles": [           {             "name": "martin",             "car": "lexus",             "age": 34,             "profiles": []           }         ]       }     ]   } ] 

this expected output.

[   {     "name": "bill",     "car": "jaguar",     "age": 30,   },{     "name": "stacey",     "car": "lambo",     "age": 23,   },{     "name": "martin",     "car": "lexus",     "age": 34,   } ] 

each profiles array can have n amount of items, may or may not have empty array of sub profiles. note converted array objects don't contain profiles after conversion.

i'm open using underscore or lodash achieve this.

let's call original data o, combining array.prototype.reduce recursion came this:

o.reduce(function recur(accumulator, curr) {    var keys = object.keys(curr);    keys.splice(keys.indexof('profiles'), 1);     accumulator.push(keys.reduce(function (entry, key) {        entry[key] = curr[key];        return entry;    }, {}));     if (curr.profiles.length) {        return accumulator.concat(curr.profiles.reduce(recur, []));    }     return accumulator; }, []); 

Comments

Popular posts from this blog

python - pip install -U PySide error -

arrays - C++ error: a brace-enclosed initializer is not allowed here before ‘{’ token -

cytoscape.js - How to add nodes to Dagre layout with Cytoscape -