I am doing this on the client with Javascript. I want to convert:
[ { "id": 10, "name": "Designer", "slug": "designer", "children": [ { "id": 11, "name": "UI / Visual Designer", "slug": "ui-visual-designer", "children": [] }, ... ] }, { "id": 1, "name": "Software Engineer", "slug": "software-engineer", "children": [ { "id": 2, "name": "Back-End Developer", "slug": "back-end-developer", "children": [] }, ... ] }, ... ]
in it:
[ { "id": 10, "text": "Designer" }, { "id": 11, "text": "UI / Visual Designer", }, { "id": 1, "text": "Software Engineer", }, { "id": 2, "text": "Back-End Developer", } ... ]
I train with map and reduce , so I try to avoid for loops (the first thing I did). This is the current code I have:
var jobNewPage = { ... buildArrayForSelect(array) { "use strict"; return $.extend(true, [], array).reduce(function(total, item) { if ( item.slug == 'remote' ) return total; total.push({ 'id' : item.id, 'text' : item.name }); let children = item.children; if (children && children.length) {
So, as you can see, I had to call jobNewPage.buildArrayForSelect(children) to do this recursively. I tried calling this.buildArrayForSelect(children) , but the context is different. I believe that this is not the best option, because I do not want to depend on calling a global variable inside a function in an object. How can I improve it?